Sunday, 25 September 2016

Java, pass-by-value, reference variables

I have a problem with understanding the "pass-by-value" action of Java in the following example:



public class Numbers {


static int[] s_ccc = {7};
static int[] t_ccc = {7};

public static void calculate(int[] b, int[] c) {

System.out.println("s_ccc[0] = " + s_ccc[0]); // 7
System.out.println("t_ccc[0] = " + t_ccc[0]); // 7

b[0] = b[0] + 9;

System.out.println("\nb[0] = " + b[0]); // 16

c = b;
System.out.println("c[0] = " + c[0] + "\n"); // 16
}

public static void main(String[] args) {

calculate(s_ccc, t_ccc);


System.out.println("s_ccc[0] = " + s_ccc[0]); // 16
System.out.println("t_ccc[0] = " + t_ccc[0]); // 7
}
}


I know that because s_ccc is a reference variable, when I give it to the method calculate() and I make some changes to its elements in the method, the changes remain even after I leave the method. I think that the same should be with t_ccc. It is again
a reference variable, I give it to the method calculate(), and in the method I change the referece to t_ccc to be that of s_ccc. Now t_ccc should be a reference variable pointing to an array, which has one element of type int equals to 16. But when the method calculate() is left, it seems that t_ccc points its old object. Why is this happening? Shouldn't the change remain for it, too? It is a reference variable after all.



Regards

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...