Java Reference
In-Depth Information
The
enhanced
for
statement
iterates through the elements of an array
without
using a
counter, thus avoiding the possibility of “stepping outside” the array. We show how to use
the enhanced
for
statement with the Java API's prebuilt data structures (called collections)
in Section 7.16. The syntax of an enhanced
for
statement is:
for
(
parameter
:
arrayName
)
statement
where
parameter
has a
type
and an
identifier
(e.g.,
int
number
), and
arrayName
is the array
through which to iterate. The type of the parameter must be
consistent
with the type of the
elements in the array. As the next example illustrates, the identifier represents successive
element values in the array on successive iterations of the loop.
Figure 7.12 uses the enhanced
for
statement (lines 12-13) to sum the integers in an
array of student grades. The enhanced
for
's parameter is of type
int
, because
array
con-
tains
int
values—the loop selects one
int
value from the array during each iteration. The
enhanced
for
statement iterates through successive values in the array one by one. The
statement's header can be read as “for each iteration, assign the next element of
array
to
int
variable
number
, then execute the following statement.” Thus, for each iteration, iden-
tifier
number
represents an
int
value in
array
. Lines 12-13 are equivalent to the following
counter-controlled repetition used in lines 12-13 of Fig. 7.5 to total the integers in
array
,
except that
counter
cannot be accessed
in the enhanced
for
statement:
for
(
int
counter =
0
; counter < array.length; counter++)
total += array[counter];
1
// Fig. 7.12: EnhancedForTest.java
2
// Using the enhanced for statement to total integers in an array.
3
4
public
class
EnhancedForTest
5
{
6
public
static
void
main(String[] args)
7
{
8
int
[] array = {
87
,
68
,
94
,
100
,
83
,
78
,
85
,
91
,
76
,
87
};
9
int
total =
0
;
10
11
// add each element's value to total
for
(
int
number : array)
total += number;
12
13
14
15
System.out.printf(
"Total of array elements: %d%n"
, total);
16
}
17
}
// end class EnhancedForTest
Total of array elements: 849
Fig. 7.12
|
Using the enhanced
for
statement to total integers in an array.
The enhanced
for
statement can be used
only
to obtain array elements—it
cannot
be
used to
modify
elements. If your program needs to modify elements, use the traditional
counter-controlled
for
statement.