"Why does the value of r change to 2 2 while it's re that I am changing, that too in another function?"
class Ideone {// main
public static void main(String[] args) throws java.lang.Exception {
int[] r = new int[2];
for (int i = 0; i < r.length; i++)
System.out.println(r[i]);
int[] catch1 = doesThisWork(1, 2, r);
// the value of r changes!?
for (int i = 0; i < r.length; i++)
System.out.println(r[i]);
}// doesthisWork
public static int[] doesThisWork(int a, int b, int[] re) {
for (int i = 0; i < re.length; i++) {
re[i] = b;
}
return re;
}
}
doesThisWork
accepts a reference to ther
array, which means it is able to change the contents of that array. While assigning a new value to there
variable inside the method wouldn't change the value ofr
when the method returns (since Java is a pass by value language), changing the state of the object referred byre
(which is an array in your case), affects the state ofr
, sincer
andre
refer to the same object.