Java Reference
In-Depth Information
In Section 5.8, we show a case in which a
for
statement cannot be represented with an
equivalent
while
statement. Typically,
for
statements are used for counter-controlled rep-
etition and
while
statements for sentinel-controlled repetition. However,
while
and
for
can each be used for either repetition type.
Scope of a
for
Statement's Control Variable
If the
initialization
expression in the
for
header declares the control variable (i.e., the con-
trol variable's type is specified before the variable name, as in Fig. 5.2), the control variable
can be used
only
in that
for
statement—it will not exist outside it. This restricted use is
known as the variable's
scope
. The scope of a variable defines where it can be used in a
program. For example, a
local variable
can be used
only
in the method that declares it and
only
from the point of declaration through the end of the method. Scope is discussed in
detail in Chapter 6, Methods: A Deeper Look.
Common Programming Error 5.3
When a
for
statement's control variable is declared in the initialization section of the
for
's header, using the control variable after the
for'
s body is a compilation error.
Expressions in a
for
Statement's Header Are Optional
All three expressions in a
for
header are optional. If the
loopContinuationCondition
is
omitted, Java assumes that the loop-continuation condition is
always true
, thus creating an
infinite loop
. You might omit the
initialization
expression if the program initializes the
control variable
before
the loop. You might omit the
increment
expression if the program
calculates the increment with statements in the loop's body or if no increment is needed.
The increment expression in a
for
acts as if it were a standalone statement at the end of
the
for
's body. Therefore, the expressions
counter = counter +
1
counter +=
1
++counter
counter++
are equivalent increment expressions in a
for
statement. Many programmers prefer
coun-
ter++
because it's concise and because a
for
loop evaluates its increment expression
after
its body executes, so the postfix increment form seems more natural. In this case, the vari-
able being incremented does not appear in a larger expression, so preincrementing and
postincrementing actually have the
same
effect.
Common Programming Error 5.4
Placing a semicolon immediately to the right of the right parenthesis of a
for
header makes
that
for
's body an empty statement. This is normally a logic error.
Error-Prevention Tip 5.4
Infinite loops occur when the loop-continuation condition in a repetition statement never
becomes
false
. To prevent this situation in a counter-controlled loop, ensure that the
control variable is modified during each iteration of the loop so that the loop-continuation
condition will eventually become
false
. In a sentinel-controlled loop, ensure that the sen-
tinel value is able to be input.