Java Reference
In-Depth Information
cludes an initializer list, it
counts
the number of initializers in the list to determine the size
of the array, then sets up the appropriate
new
operation “behind the scenes.”
The application in Fig. 7.3 initializes an integer array with 10 values (line 9) and dis-
plays the array in tabular format. The code for displaying the array elements (lines 14-15)
is identical to that in Fig. 7.2 (lines 15-16).
1
// Fig. 7.3: InitArray.java
2
// Initializing the elements of an array with an array initializer.
3
4
public class
InitArray
5
{
6
public static void
main(String[] args)
7
{
8
// initializer list specifies the initial value for each element
int
[] array = {
32
,
27
,
64
,
18
,
95
,
14
,
90
,
70
,
60
,
37
};
9
10
11
System.out.printf(
"%s%8s%n"
,
"Index"
,
"Value"
);
// column headings
12
13
// output each array element's value
14
for
(
int
counter =
0
; counter < array.length; counter++)
15
System.out.printf(
"%5d%8d%n"
, counter, array[counter]);
16
17
}
// end class InitArray
Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Fig. 7.3
|
Initializing the elements of an array with an array initializer.
The application in Fig. 7.4 creates a 10-element array and assigns to each element one of
the even integers from 2 to 20 (
2
,
4
,
6
, …,
20
). Then the application displays the array in
tabular format. The
for
statement at lines 12-13 calculates an array element's value by
multiplying the current value of the control variable
counter
by
2
, then adding
2
.
1
// Fig. 7.4: InitArray.java
2
// Calculating the values to be placed into the elements of an array.
3
4
public class
InitArray
5
{
Fig. 7.4
|
Calculating the values to be placed into the elements of an array. (Part 1 of 2.)