Java Reference
In-Depth Information
Note that the type of the array variable ( int [] ) does not include the size of the
array. The instantiation of height , using the new operator, reserves the memory
space to store 11 integers indexed from 0 to 10. Once an array is declared to be a
certain size, the number of values it can hold cannot be changed.
The example shown in Listing 8.1 creates an array called list that can hold
15 integers, which it loads with successive increments of 10. It then changes the
value of the sixth element in the array (at index 5). Finally, it prints all values
stored in the array.
Figure 8.2 shows the array as it changes during the execution of the BasicArray
program. It is often convenient to use for loops when handling arrays, because the
number of positions in the array is constant. Note that a constant called LIMIT is
used in several places in the BasicArray program. This constant is used to declare
the size of the array and to control the for loop that initializes the array values.
The iterator version of the for loop is used to print the values in the array.
Recall from Chapter 5 that this version of the for loop extracts each value in the
VideoNote
Overview of arrays.
After three
iterations of the
first loop
The array is created
with 15 elements,
indexed from 0 to 14
After completing
the first loop
After changing
the value of
list[5]
0
0
0
10
20
0
0
10
20
30
0
0
10
20
30
1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4
40
50
60
70
40
999
60
70
5
6
7
8
5
6
7
8
5
6
7
8
5
6
7
8
80
90
100
110
80
90
100
110
9
10
11
12
9
10
11
12
9
10
11
12
9
10
11
12
120
130
140
120
130
140
13
14
13
14
13
14
13
14
FIGURE 8.2 The array list as it changes in the BasicArray program
Search WWH ::




Custom Search