Search code examples
javapass-by-referencepass-by-value

Pass by reference versus value in variable versus array element


I know this question apparently has many duplicates like here and here.

My question is different though.

Consider the following example:

public class MyClass {
    public static void test(int a, int b) {
        System.out.println("In test() at start: "+a+" "+b);
        int temp=a;
        a=b;
        b=temp;
        System.out.println("In test() at end: "+a+" "+b);
    }

    public static void main(String args[]) {
        int a=1, b=2;
        System.out.println("a: "+a+" b: "+b);

        test(a, b);
        System.out.println("a: "+a+" b: "+b);
    }
}

The output that I get for the above snippet is:

a: 1 b: 2
In test() at start: 1 2
In test() at end: 2 1
a: 1 b: 2

This shows that the original values of a and b in main() have not been swapped when I called test(), thereby implying (if I understand correctly) that it was passed by value.

Now, consider the following code snippet:

public class MyClass {
    public static void test(int[] arr) {
        System.out.println(arr[2]);
        arr[2]=20;
        System.out.println(arr[2]);
    }

    public static void main(String args[]) {
        int[] arr={0,1,2,3,4,5};
        System.out.println(arr[2]);

        test(arr);
        System.out.println(arr[2]);
    }
}

The output that I get for this code snippet is:

2
2
20
20

This shows that the value at arr[2] was changed in the original array in main(), thereby denoting (if I understand correctly) that the array was passed by reference.

Could someone please point out what is going on? Why does it show different behaviors?

Thanks!


Solution

  • Primitive datatype variables will be passed by value. Object datatype variables will be passed by reference. Array is Object datatype, so it will be passed by reference.