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