Java Reference
In-Depth Information
The first part of the definition specifies the type of the array. The element type name,
int
in this case,
is followed by an empty pair of square brackets to indicate you are declaring an array rather than a single
variable of type
int
. The part of the statement that follows the equal sign defines the array. The keyword
new
indicates that you are allocating new memory for the array, and
int[10]
specifies you want capacity
for 10 variables of type
int
in the array. Because each element in the
primes
array is a variable of type
int
that requires 4 bytes, the whole array occupies 40 bytes, plus 4 bytes for the
primes
variable to store the ref-
erence to the array. When an array is created like this, all the array elements are initialized to a default value
automatically. The initial value is zero in the case of an array of numerical values, is
false
for
boolean
arrays, is
'\u0000'
for arrays storing type
char
, and is
null
for an array of objects of a class type.
Consider the following statement:
double[] myArray = new double[100];
This statement is a declaration of the array variable
myArray
. The statement also defines the array be-
cause the array size is specified. The variable
myArray
refers to an array of 100 values of type
double
, and
each element has the value 0.0 assigned by default. Because there are 100 elements in this array, the legal
index values range from 0 to 99.
The Length of an Array
You can refer to the length of the array — the number of elements it contains — using
length
, a data mem-
ber of the
array
object. For example, for the array
myArray
that you defined in the previous section, you
can refer to its length as
myArray.length
, which has the value 100. You can use the
length
member of an
array to control a numerical
for
loop that iterates over the elements of an array.
Accessing Array Elements
As I said earlier, you refer to an element of an array by using the array name followed by the element's index
value enclosed between square brackets. You can specify an index value by any expression that produces a
zero or positive result of type
int
. If you use a value of type
long
as an index, you get an error message
from the compiler; if your calculation of an index uses
long
variables and the result is of type
long
, you