Problem with assigning an array to other array in Java

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

Leave a Comment