Java Reference
In-Depth Information
myList[ 4 ] = 4.0 ;
myList[ 5 ] = 34.33 ;
myList[ 6 ] = 34.0 ;
myList[ 7 ] = 45.45 ;
myList[ 8 ] = 99.993 ;
myList[ 9 ] = 11123 ;
This array is illustrated in Figure 6.1.
double [] myList = new double [ 10 ];
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
5.6
4.5
3.3
13.2
4.0
34.33
34.0
45.45
99.993
11123
Array reference
variable
Array element at
index 5
myList[5]
Element value
myList[6]
myList[7]
myList[8]
myList[9]
F IGURE 6.1
The array myList has ten elements of double type and int indices from 0 to 9 .
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 ref-
erence to an array of ten double elements.
array vs. array variable
6.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
6.2.4 Array Indexed Variables
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 6.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] .
 
Search WWH ::




Custom Search