Java Reference
In-Depth Information
The flowchart of the statement is shown in Figure 4.3b. The
for
loop initializes
i
to
0
, then
repeatedly executes the
println
statement and evaluates
i++
while
i
is less than
100
.
The
initial-action
,
i = 0
, initializes the control variable,
i
. The
loop-
continuation-condition
,
i < 100
, is a Boolean expression. The expression is evaluated
right after the initialization and at the beginning of each iteration. If this condition is
true
,
the loop body is executed. If it is
false
, the loop terminates and the program control turns to
the line following the loop.
The
action-after-each-iteration
,
i++
, is a statement that adjusts the control vari-
able. This statement is executed after each iteration and increments the control variable. Even-
tually, the value of the control variable should force the
loop-continuation-condition
to become
false
; otherwise, the loop is infinite.
The loop control variable can be declared and initialized in the
for
loop. Here is an example:
initial-action
action-after-each-iteration
for
( ; i <
100
; i++) {
System.out.println(
"Welcome to Java!"
);
int
i =
0
}
If there is only one statement in the loop body, as in this example, the braces can be omitted.
omitting braces
Tip
The control variable must be declared inside the control structure of the loop or before
the loop. If the loop control variable is used only in the loop, and not elsewhere, it is
good programming practice to declare it in the
initial-action
of the
for
loop. If
the variable is declared inside the loop control structure, it cannot be referenced outside
the loop. In the preceding code, for example, you cannot reference
i
outside the
for
loop, because it is declared inside the
for
loop.
declare control variable
Note
The
initial-action
in a
for
loop can be a list of zero or more comma-separated
variable declaration statements or assignment expressions. For example:
for
loop variations
for
(
int
i =
0
, j =
0
; (i + j <
10
); i++, j++) {
// Do something
}
The
action-after-each-iteration
in a
for
loop can be a list of zero or more
comma-separated statements. For example:
for
(
int
i =
1
; i <
100
;
System.out.println(i), i++
);
This example is correct, but it is a bad example, because it makes the code difficult to
read. Normally, you declare and initialize a control variable as an initial action and incre-
ment or decrement the control variable as an action after each iteration.
Note
If the
loop-continuation-condition
in a
for
loop is omitted, it is implicitly
true
. Thus the statement given below in (a), which is an infinite loop, is the same
as in (b). To avoid confusion, though, it is better to use the equivalent loop in (c).
for
( ;
true
;) {
// Do something
while
(
true
) {
// Do something
for
( ; ; ) {
// Do something
Equivalent
Equivalent
}
}
}
This is better
(a)
(b)
(c)