Thursday 11 February 2016

variables - How does pointing to objects work in java?



So, lets say I have 2 arrays defined like this:




int[] a = {1,2,3};
int[] b = a;

a[1] = 35; // b[1] becomes 35
b[0] = -5; // why would a[0] become -5?


So, I can reason that changing a value in a will automatically change the value in b (b is pointing to a). But, if I change value in b, why would it affect a? Wouldn't that be as if a is pointing to b (they are interchangeable)?



I was confused with this concept and would like some clarification.

Any advice would be appreciated. Thanks.


Answer



Let's do an analogy here. The objects (such as arrays) that you create are like balloons. And the variables (a and b) are like children. And the children can hold a single balloon with a string. And that string is what we call a reference. On the other hand, one balloon can be held by multiple children.



In your code, you created a single balloon i.e. an array {1, 2, 3}. And let a child called a hold it. Now you can tell child a to modify items in the array because the child a is holding it.



In the second line, you tell another child b to hold the balloon that a is holding, like this:



int[] b = a;



Now a and b are actually holding the same balloon!



When you do this:



a[1] = 35;


Not only is the balloon that a is holding been changed, but also is the balloon held by b been changed. Because, well, a and b are holding the same balloon.




The same thing happens when you do:



b[0] = -5;


That's how reference types work in Java. But please note that this doesn't apply to primitive types, such as int or float.



For example,



int a = 10;

int b = a;
b = 20; //a is not equal to 20!!!

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...