Java Reference
In-Depth Information
PITFALL: (continued)
Array types are reference types; that is, an array variable contains the memory address
of the array it names. The assignment operator copies this memory address. For exam-
ple, consider the following code:
double [] a = new double [10];
double [] b = new double [10];
int i;
for (i = 0; i < a.length; i++)
a[i] = i;
b = a;
System.out.println("a[2] = " + a[2] + " b[2] = " + b[2]);
a[2] = 42;
System.out.println("a[2] = " + a[2] + " b[2] = " + b[2]);
This will produce the following output:
a[2] = 2.0 b[2] = 2.0
a[2] = 42.0 b[2] = 42.0
The assignment statement b = a; copies the memory address from a to b so that the
array variable b contains the same memory address as the array variable a . After the
assignment statement, a and b are two different names for the same array. Thus, when
we change the value of a[2] , we are also changing the value of b[2] .
Unless you want two array variables to be two names for the same array (and on rare
occasions you do want this), you should not use the assignment operator with arrays. If
you want the arrays a and b in the preceding code to be different arrays with the same
values in each index position, then instead of the assignment statement
b = a;
you need to use something like the following:
int i;
for (i = 0; (i < a.length) && (i < b.length); i++)
b[i] = a[i];
Note that the above code will not make b an exact copy of a , unless a and b have the
same length.
(continued)
Search WWH ::




Custom Search