Java Reference
In-Depth Information
To illustrate this, suppose you have the following in some method definition,
double [] a = new double [10];
double [] b = new double [30];
and suppose that the elements of the arrays a and b have been given values. Both of the
following are then legal method invocations:
SampleClass.doubleArrayElements(a);
SampleClass.doubleArrayElements(b);
Note that no square brackets are used when you give an entire array as an argument to
a method.
An array type is a reference type just as a class type is, so, as with a class type argu-
ment, a method can change the data in an array argument. To phrase it more precisely,
a method can change the values stored in the indexed variables of an array argument.
This is illustrated by the preceding method doubleArrayElements .
An array type parameter does not specify the length of the array argument that may
be plugged in for the parameter. An array knows its length and stores it in the length
instance variable. The same array parameter can be replaced with array arguments of
different lengths. Note that the preceding method doubleArrayElements can take an
array of any length as an argument.
length of
array
arguments
PITFALL: Use of = and == with Arrays
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:
assignment
with arrays
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
Search WWH ::




Custom Search