Java Reference
In-Depth Information
Note
An array variable that appears to hold an array actually contains a reference to that array.
Strictly speaking, an array variable and an array are different, but most of the time the
distinction can be ignored. Thus it is all right to say, for simplicity, that myList is an
array, instead of stating, at greater length, that myList is a variable that contains a
reference to an array of ten double elements.
array vs. array variable
7.2.3 Array Size and Default Values
When space for an array is allocated, the array size must be given, specifying the number of ele-
ments that can be stored in it. The size of an array cannot be changed after the array is created.
Size can be obtained using arrayRefVar.length . For example, myList.length is 10 .
When an array is created, its elements are assigned the default value of 0 for the numeric
primitive data types, \u0000 for char types, and false for boolean types.
array length
default values
7.2.4 Accessing Array Elements
The array elements are accessed through the index. Array indices are 0 based; that is, they
range from 0 to arrayRefVar.length-1 . In the example in FigureĀ 7.1, myList holds ten
double values, and the indices are from 0 to 9 .
Each element in the array is represented using the following syntax, known as an indexed
variable :
0 based
indexed variable
arrayRefVar[index];
For example, myList[9] represents the last element in the array myList .
Caution
Some programming languages use parentheses to reference an array element, as in
myList(9) , but Java uses brackets, as in myList[9] .
An indexed variable can be used in the same way as a regular variable. For example, the
following code adds the values in myList[0] and myList[1] to myList[2] .
myList[ 2 ] = myList[ 0 ] + myList[ 1 ];
The following loop assigns 0 to myList[0] , 1 to myList[1] , . . . , and 9 to myList[9] :
for ( int i = 0 ; i < myList.length; i++) {
myList[i] = i;
}
7.2.5 Array Initializers
Java has a shorthand notation, known as the array initializer , which combines the declaration,
creation, and initialization of an array in one statement using the following syntax:
array initializer
elementType[] arrayRefVar = {value0, value1, ..., value k };
For example, the statement
double [] myList = { 1.9 , 2.9 , 3.4 , 3.5 };
declares, creates, and initializes the array myList with four elements, which is equivalent to
the following statements:
double [] myList = new double [ 4 ];
myList[ 0 ] = 1.9 ;
myList[ 1 ] = 2.9 ;
 
 
Search WWH ::




Custom Search