Arrays are treated as Objects in Java and, as such, obey the same rules for equality and assignment. We recall these here in the context of arrays.
An array variable is a reference variable. It stores information about where to locate the array elements. As a result, all array variables require the same amount of storage, namely one machine word, irrespective of the size of the arrays or the nature of their elements. For example, when an array variable is initialised by
int[] a = new int[20];storage is obtained for 20 integers and the address of that block of memory (or some record that includes it) is placed in the variable a. If we now declare another array variable
int[] b;and make the assignment
b = a;the variable b now holds the same address as a. But there is still only one array; there are now two ways of addressing it. Any change to b[i] will change a[i] identically, and conversely, because they refer to one and the same memory location. For that reason, array variable assignment should be used with caution.
If you want to create a copy of an array, you have to work harder, for example:
b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
There are now two distinct arrays, of the same length and with the
same contents. Change to either will leave the other unaffected.
(Note that if a and b were arrays of objects, rather than
arrays of primitive types, the two arrays might still refer to
overlapping data, but we shall not pursue that further here.)