Java Reference
In-Depth Information
loop and the
while
keyword to mark the end and introduce the loop condition.
Also, unlike the
while
loop, the
do
loop is terminated with a semicolon. This is
because the
do
loop ends with the loop condition rather than simply ending with a
curly brace that marks the end of the loop body. The following
do
loop prints the
same output as the
while
loop just discussed:
a
x
int
count
=
0
;
do
{
System
.
out
.
println
(
count
);
count
++;
}
while
(
count
<
10
);
The
do
loop is much less commonly used than its
while
cousin because, in practice,
it is unusual to encounter a situation where you are sure you always want a loop to
execute at least once.
The for Statement
The
for
statement provides a looping construct that is often more convenient than
the
while
and
do
loops. The
for
statement takes advantage of a common looping
pattern. Most loops have a counter, or state variable of some kind, that is initialized
before the loop starts, tested to determine whether to execute the loop body, and
then incremented or updated somehow at the end of the loop body before the test
expression is evaluated again. The initialization, test, and update steps are the three
crucial manipulations of a loop variable, and the
for
statement makes these three
steps an explicit part of the loop syntax:
for
(
initialize
;
test
;
update
)
{
statement
}
This
for
loop is basically equivalent to the following
while
loop:
initialize
;
while
(
test
)
{
statement
;
update
;
}
Placing the
initialize
,
test
, and
update
expressions at the top of a
for
loop
makes it especially easy to understand what the loop is doing, and it prevents mis‐
takes such as forgetting to initialize or update the loop variable. The interpreter dis‐
cards the values of the
initialize
and
update
expressions, so to be useful, these
expressions must have side effects.
initialize
is typically an assignment expression
while
update
is usually an increment, decrement, or some other assignment.
The following
for
loop prints the numbers 0 to 9, just as the previous
while
and
do
loops have done: