Java Reference
In-Depth Information
for (type identifier : iterable_expression) {
// statements
}
You can't fully appreciate the capabilities of this loop until you have learned about arrays in Chapter 4
and
Collection
classes in Chapter 14, so I just give you a brief indication here of what you can do with
it so you know about all the loop statements you have available. This
for
loop has two control elements
separated by a colon that appear between the parentheses following the
for
keyword. The first element is an
identifier
of the type that you specify, and the second is an expression specifying a collection of objects
or values of the specified type. The loop executes once for each item of the specified type that appears in the
collection, and you can refer to the current item in the loop body using the
identifier
that you specified
as the first control element.
3. The While Loop
while (expression) {
// statements
}
This loop executes as long as the logical expression between the parentheses is
true
. When
expression
is
false
, the loop ends and execution continues with the statement following the loop block. The expression
is tested at the beginning of the loop, so if it is initially
false
, the loop body is not executed at all. An
example of a
while
loop condition might be
yesNo==
'
y
'
|| yesNo==
'
y
'. This expression is
true
if the vari-
able
yesNo
contains '
y
' or '
y
,' so
yesNo
might hold a character entered from the keyboard in this instance.
4. The Do-While Loop
do {
// statements
} while (expression);
This loop is similar to the
while
loop, except that the expression controlling the loop is tested at the end
of the loop block. This means that the loop body always executes at least once, even if the expression is
always
false
.
The basic logic of each of the four kinds of loop is shown in
Figure 3-6
.