-
Notifications
You must be signed in to change notification settings - Fork 0
Methods
A method in Java is a collection of statements that are grouped together to perform an operation, it has inputs (can be multiple) and a single output (the return value).
Structure of a method is as follows:
private static double findAverage(double[] numbers) {
// Method Body
double sum = 0.0;
for (double e : numbers)
sum += e;
return sum / numbers.length;
}-
private static double findAverage(double[] numbers)is the method header. -
double is the return type.
-
findAverageis the method name. -
double[] numbersare the method parameters. -
Methods may have a return statement, they do not need to have it if their return type is void.
private static int max(int a, int b) {
int result = a;
if (b > a)
result = b;
return result;
}int input1 = 5;
int input2 = 8;
int o = max(input1,input2);When we call max with input1 and input2, they are Argument Values. They are passed to the method parameters int a and int b.
Result is passed to the output variable o.
When a method is called, an activation record (or activation frame) is created. It has the parameters and other variables of the method.
When an activation record is created for a method, it is stored in an area of the memory, referred as call stack. Call stack can also be called as runtime stack, machine stack or just stack.
When a new method is called inside a method, the caller method's activation record stays and a new activation method is created for the method that has been called.
When a method returns, its activation record is removed from the stack.
Example:
public class AppMethods {
public static void main(String[] args) {
int input1 = 5;
int input2 = 8;
int o = max(input1,input2);
System.out.println("Bigger number is: " + o);
}
private static int max(int a, int b) {
int result = a;
if (b > a)
result = b;
foo(result);
return result;
}
private static void foo(int result) {
System.out.println("Foo works");
}
}The arguments are passed by value to parameters when invoking a method, but it is only applicable to primitive types: int, long, float, double, boolean (for example, not an array)
This means that variables in the caller method are not affected by changes made to the parameters inside the method, if they are primitive type.
How do we pass non primitive types? Pass by Reference. We can see how that works is an example:
public class AppPassValueReference {
public static void main(String[] args) {
int age = 23; // primitive type
int[] numbers = {8,5,3}; // array is a reference type
System.out.println("Before: Age=" + age + ", Numbers=" + Arrays.toString(numbers));
modifyValues(age, numbers);
System.out.println("After : Age=" + age + ", Numbers=" + Arrays.toString(numbers));
}
private static void modifyValues(int age, int[] b) {
age = 2;
b[0] = 2;
}
}