Is Java Pass-by-Value or Pass-by-Reference?

Is Java Pass-by-Value or Pass-by-Reference?
Is Java Pass-by-Value or Pass-by-Reference?

There is a lot of confusion on whether Java uses pass-by-reference or pass-by-value before we even conclude. Let's understand these concepts in detail.

Common jargons 🤓

The method/behavior which calls other method/behavior is caller.
The method/behavior which gets called is callee.

In the below example, main is caller, and callee is add.

public class JavaReference {

    // Caller
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        add(a,b);
    }

    // Callee
    public static void add(int a, int b){
        int result = a+b;
        System.out.println(result);
    }
}

Now to concepts

Pass-by-Value:

In this, the caller and the callee method both make a copy of the value. Changing the value in callee doesn't affect the value in the original variables.

Pass-by-Reference:

Here variable's pointer(the memory address) is passed to the callee, i.e., any changes to variables in the callee method are reflected in the caller's variable.

Detail of a variable

Conclusion:

So what does Java follow? In short, BOTH. Yes, you heard me right. Java does it very intelligently, which is why many people are confused. Let's understand how

You might know Java kept primitive variables around for developers who still want to use them for simple scenarios. Whenever we use primitive values or immutable objects, they use pass-by-value.

public class JavaReference {

    // Caller
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        add(a,b);
        System.out.println("Result from main : "+ (a+b));
    }

    // Callee
    public static void add(int a, int b){
        a=12;
        b=15;
        int result = a+b;
        System.out.println("Result from add : "+result);
    }
}

/*
Output:
    Result from add : 27
    Result from main : 30
*/
Example of pass-by-value

Whenever you are passing a mutable object, it uses pass-by-reference. i.e., the pointer (variable memory address) to the object is passed.

public class JavaReference {

    // Caller
    public static void main(String[] args) {
        InputVal input = new InputVal(10,20);
        add(input);
        System.out.println("Result from main : "+ (input.a+input.b));
    }

    // Callee
    public static void add(InputVal inputValues){
       inputValues.a = 12;
       inputValues.b = 15;
       int result = inputValues.a + inputValues.b;
       System.out.println("Result from add : "+result);
    }

    // Inner Class
    static class InputVal{
        Integer a;
        Integer b;

        public InputVal(Integer a, Integer b) {
            this.a = a;
            this.b = b;
        }
    }
}

/*
Output:
    Result from add : 27
    Result from main : 27
*/
Example of pass-by-reference