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?