In Java, byte arrays are a special type of objects. In this case you're using integer arrays that have type I[
. In Java, object instances are always referenced rather than kept by value. You can nicely see what happens if you print them out:
int[] a = { 1, 2, 3, 4 };
int[] b = { 5, 6, 7, 8 };
System.out.printf("Before: a=%s b=%s%n", a, b);
a = b;
System.out.printf("After: a=%s b=%s%n", a, b);
b[2] = 9;
System.out.println(Arrays.toString(a));
will print out:
Before: a=[I@15db9742 b=[I@6d06d69c
After: a=[I@6d06d69c b=[I@6d06d69c
[5, 6, 9, 8]
As you can see it prints out the references as the type I[
, then an @
and then the reference. First the reference points to two different object instances, but after a = b
, both a
and b
reference the object instance that was first assigned to b
. This means that any alteration of a
and b
will on the same object. Of course it then doesn't matter if you print out the values of a
or b
either.
If you want to make sure that a
isn't altered when b
is changed then you need to clone the object. Cloning is supported for arrays as they implement the Cloneable
interface:
int[] a = { 1, 2, 3, 4 };
int[] b = { 5, 6, 7, 8 };
System.out.printf("Before: a=%s b=%s%n", a, b);
a = b.clone();
System.out.printf("After: a=%s b=%s%n", a, b);
b[2] = 9;
System.out.println(Arrays.toString(a));
will print out:
Before: a=[I@15db9742 b=[I@6d06d69c
After: a=[I@7852e922 b=[I@6d06d69c
[5, 6, 7, 8]
As you can see a
now points to a brand new array instance with the original values first referenced by b
.
Note that printing the object references works for arrays because arrays don't implement toString
, which is called automatically when a String
is expected. In that case it uses Object#toString
which prints the references as shown here.
You cannot print out the references to object instances if toString
is implemented. Instead you can use System.identityHashCode(variable)
for an indication if the references are equal. Or you could simply use if (a == b)
to test for reference equality of course.