Java Reference
In-Depth Information
Exercise 10.5
: Write a method that takes two
char
parameters and
prints the characters between those two values, including the endpoints.
10.5.2. Enhanced
for
Statement
The enhanced
for
statement, often referred to as the
for-each
loop,
provides an alternative, more compact form for iterating through a set
of values. It looks like this:
for (
Type loop-variable
:
set-expression
)
statement
The
set-expression
must evaluate to an object that defines the set of
values that you want to iterate through, and the
loop-variable
is a local
variable of a suitable type for the set's contents. Each time through the
loop,
loop-variable
takes on the next value from the set, and
statement
is
executed (presumably using the
loop-variable
for something). This con-
tinues until no more values remain in the set.
The
set-expression
must either evaluate to an array instance, or an ob-
ject that implements the interface
java.lang.Iterable
which is the case
for all of the collection classes you'll see in
Chapter 21
. Here's an ex-
ample using an array, where we rewrite the
average
method we showed
on page
19
:
static double average(int[] values) {
if (values == null || values.length == 0)
throw new IllegalArgumentException();
double sum = 0.0;
for (int val : values)
sum += val;
return sum / values.length;
}