Java Reference
In-Depth Information
In Java, data is either a primitive data type or an object. Because arrays
are not one of the eight primitive data types, they must be objects.
Therefore, an array requires a reference to access it and the new keyword
to instantiate it.
Use square brackets to declare an array reference. For example, the follow-
ing statement declares a reference to an array of ints:
int [] sums;
In Java, you can also declare an array with the square brackets following
the variable name, instead of preceding it. For example, sums can be
declared as follows:
int sums [];
This is for compatibility with C and C++. My preference is to place the
square brackets before the variable name, because it makes the reference
declaration clearer.
The sums reference can refer to any array of ints, no matter how many ele-
ments are in the array. Because sums is a reference, it can also be assigned to
null.
The size of the array is determined when the array is instantiated. An int is
placed in square brackets to specify the size. For example, the following state-
ment assigns sums to a new array of 20 ints:
sums = new int[20];
Because an array must be in contiguous memory, its size cannot be changed
after the memory is initially allocated. If the array of size 20 is deemed too
small, a new larger array is instantiated and the old array is garbage collected.
For example, the following statement assigns sums to a larger array of 30 ints:
sums = new int[30];
The array of 20 ints is garbage collected, assuming that it is no longer being
referenced in your program. Assigning sums to an array of 20 ints and then to
an array of 30 ints demonstrates how sums can refer to any size array of ints.
An array reference can be declared and the array object can be instantiated
in the same statement. The following statement declares temps a reference to
an array of doubles, and temps is assigned to a new array of 31 doubles in the
same statement:
double [] temps = new double[31];
Search WWH ::




Custom Search