Java Reference
In-Depth Information
• The expression that gets executed at the end of each loop iteration, just
prior to retesting the conditional
Example 3.11
A Java
for
loop
for (i = 0; i < 8; i++) {
System.out.println(i);
}
Unlike C/C++, Java doesn't have the comma operator for use within arbi-
trary expressions, but the comma is supported as special syntax in Java
for
loops. It makes it possible to have multiple initializers in the opening of the
for
loop and multiple expressions in the portion repeated at each iteration of
the loop. The result is much the same—you can initialize and increment
multiple variables or objects in your
for
loop.
More formally, the full syntax of the
for
loop can be described with fol-
lowing meta-language as shown in Example 3.12 (where the
[]*
means “zero
or more repetitions of”).
Example 3.12
Java
for
loop syntax
for (
before
[,
before
]* ;
exit_condition
;
each_time
[,
each_time
]* )
statement
The biggest difference between C and Java
for
loops, however, is that Java
allows you to declare one or more variables of a single type in the initializing
expression of the
for
loop (Example 3.13). Such a variable's scope is the
for
loop itself, so don't declare a variable there if you want to reference it outside
the loop. It is a very handy construct, however, for enumerators, iterators, and
simple counters.
Example 3.13
A Java
for
loop with local index
for (int i = 0; i < 8; i++) {
System.out.println(i);
}