public class Test {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = a;
int[] c = {6, 7, 8};
a = c;
Suppose you think of an object as a house, and a reference as a piece of paper with the address of a house written on it. a
, b
, and c
are all references. So when you say
int[] a = {1, 2, 3, 4, 5};
you're building a house with 1, 2, 3, 4, and 5 in it; and a
is a piece of paper with the address of that house.
int[] b = a;
b
is another reference, which means it's another piece of paper. But it has the address of the same house on it.
int[] c = {6, 7, 8};
a = c;
Now we build a new house and put 6, 7, and 8 into it. c
will be a piece of paper with the address of the new house. When we say a = c
, then the slip of paper that used to be a
is thrown out, and we make a new piece of paper with the address of the new house. That's the new value of a
.
But b
was a separate piece of paper. It hasn't changed. Nothing we've done has changed it.
References are like that.