Skip to content

Methods

Büşra Oğuzoğlu edited this page Jul 8, 2022 · 13 revisions

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.

  • findAverage is the method name.

  • double[] numbers are the method parameters.

  • Methods may have a return statement, they do not need to have it if their return type is void.

Method Calls:

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.

Activation Record and Call Stack:

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");
    }
}
callstack

Pass by Value vs Pass by Reference:

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;
    }
}
passbyvaluereference passbyvaluereference2

Method Overloading:

Two or more methods can have the same name but different parameter lists, this is called method overloading.

The Java compiler determines which method to use based on the method signature

public static int max(int num1, int num2) { /** Return the max of two int values */
    if (num1 > num2)
        return num1;
    else
        return num2;
}
public static double max(double num1, double num2) { /** Find the max of two double values */
    if (num1 > num2)
        return num1;
    else
        return num2;
}
public static double max(double num1, double num2, double num3) { /** Return the max of three double values */
    return max(max(num1, num2), num3);
}

Variable Length Arguments:

You can pass a variable number of arguments of the same type to a method.

Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter

Java treats a variable-length parameter as an array

public static void main(String[] args) {
    printMax(34, 3, 3, 2, 56.5); // printMax method can process variable number of arguments 
    printMax(4,6); // printMax method can process variable number of arguments
    printMax(new double[]{1, 2, 3}); // You can give an array as an argument
}
public static void printMax(double... numbers) {
    if (numbers.length == 0) {
        System.out.println("No argument passed");
    return;
}

Variable Scope:

The scope of a variable is the part of the program where the variable can be referenced

The scope of a local variable starts from its declaration and continues to the end of the block that contains that variable

As an example if we create a for loop, variable i cannot be referenced outside the loop.

for (int i = 1; i <= 4; i++) 
{
   // Scope of i starts
   ....
   // Scope of i ends
}

This code does not work:

public static void main(String[] args) 
{
    int a = 4;
    int b = 7;
    printValues();
}
private static void printValues() {
    System.out.println("a is " + a + ", b is : " + b);
}

Scope of a and b is only their block, they cannot be referenced outside the main method. (We could pass them as parameters to printValues function.)

Similary, if we create a new variable inside printValues() function and try to reach it in main method, we cannot do that.

A method parameter is also a local variable: The scope of a method parameter covers the entire method but cannot be reached outside.

private static int computeSquare(int a) {
    // Scope of a starts
    System.out.println("input is: " + a);
    System.out.println("square of the input is : " + a * a);
    return a * a;
    // Scope of a ends
}
Clone this wiki locally