The application of Fig. E.2 uses keyword new
to create an array of 10 int
elements, which are initially zero (the default for int
variables). Line 8 declares array
—a reference capable of referring to an array of int
elements. Line 10 creates the array object and assigns its reference to variable array
. Line 12 outputs the column headings. The first column contains the index (0–9) of each array element, and the second column contains the default value (0) of each array element.
1 // Fig. E.2: InitArray.java
2 // Initializing the elements of an array to default values of zero.
3
4 public class InitArray
5 {
6 public static void main( String[] args )
7 {
8 int[] array; // declare array named array
9
10 array = new int[ 10 ]; // create the array object
11
12 System.out.printf( "%s%8s
", "Index", "Value" ); // column headings
13
14 // output each array element's value
15 for ( int counter = 0; counter < array.length; counter++ )
16 System.out.printf( "%5d%8d
", counter, array[ counter ] );
17 } // end main
18 } // end class InitArray
Index Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
The for
statement in lines 15–16 outputs the index number (represented by counter
) and the value of each array element (represented by array[counter
]). The loop-control variable counter
is initially 0
—index values start at 0, so using zero-based counting allows the loop to access every element of the array. The for
’s loop-continuation condition uses the expression array.length
(line 15) to determine the length of the array. In this example, the length of the array is 10, so the loop continues executing as long as the value of control variable counter
is less than 10. The highest index value of a 10-element array is 9, so using the less-than operator in the loop-continuation condition guarantees that the loop does not attempt to access an element beyond the end of the array (i.e., during the final iteration of the loop, counter
is 9
). We’ll soon see what Java does when it encounters such an out-of-range index at execution time.