Java Reference
In-Depth Information
1
// Fig. 7.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
// declare variable array and initialize it with an array object
int [] array = new int[ 10 ]; // create the array object
9
10
11
System.out.printf( "%s%8s%n" , "Index" , "Value" ); // column headings
12
13
// output each array element's value
for ( int counter = 0 ; counter < array.length; counter++)
System.out.printf( "%5d%8d%n" , counter, array[counter]);
14
15
16
}
17
} // 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
Fig. 7.2 | Initializing the elements of an array to default values of zero.
The for statement (lines 14-15) outputs the index (represented by counter ) and value
of each array element (represented by array[counter ]). Control variable counter is initially
0 —index values start at 0, so using zero-based counting allows the loop to access every ele-
ment of the array. The for 's loop-continuation condition uses the expression array.length
(line 14) 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.
7.4.2 Using an Array Initializer
You can create an array and initialize its elements with an array initializer —a comma-sep-
arated list of expressions (called an initializer list ) enclosed in braces. In this case, the array
length is determined by the number of elements in the initializer list. For example,
int [] n = { 10 , 20 , 30 , 40 , 50 };
creates a five -element array with index values 0 - 4 . Element n[0] is initialized to 10 , n[1]
is initialized to 20 , and so on. When the compiler encounters an array declaration that in-
 
 
Search WWH ::




Custom Search