0

While debugging my Java code, I observed something unusual. Consider the following example:

public static int[] func(int[] arr) {
   int[] res=new int[]{1,2,3,4};
   return res;
}

In main function:

vals=new int[]{0,0,0,0};
vals=func(vals);
for (int i=0;i<4;i++) System.out.println(vals[i]);

When I call 'func' with 'vals' as argument and set vals to the returned array, it works fine and the values inside are that of the returned array. I get the output:

1
2
3
4

Now consider this:

public static void func2(int[] arr) {
   arr=func(vals);
}

In main function:

vals=new int[]{0,0,0,0};
func2(vals);
for (int i=0;i<4;i++) System.out.println(vals[i]);

When I call func2 with 'vals' as argument, the output is different and 'vals' retains its original values, i.e the output is:

0
0
0
0

According to me this should not happen because I am assigning 'vals' to the new array returned from 'func' called in 'func2' instead of being called directly in the main function. I would like to know why this is happening. What is the difference between the 2 scenarios?

  • Because it’s only assigned in `func2`. The variable in `main` has no relation to the variable in `func2` – Sami Kuhmonen Oct 02 '20 at 22:08
  • 1
    Java is a pass by *value*, not a pass by *reference*, language, so assigning something to the parameter of a method has no effect whatsoever to the object that was assigned to a variable that was passed to a method. – Bohemian Oct 02 '20 at 22:09
  • 1
    The rule is that you can change the _contents_ of a reference passed into a method, but not the reference itself. `arr[0] = 1; arr[1] = 2; ...` would work, but `arr = anything` won't propagate outside the method. – Louis Wasserman Oct 02 '20 at 22:20

0 Answers0