Java Reference
In-Depth Information
int
count
;
for
(
count
=
0
;
count
<
10
;
count
++)
System
.
out
.
println
(
count
);
Notice how this syntax places all the important information about the loop variable
on a single line, making it very clear how the loop executes. Placing the update
expression in the
for
statement itself also simplifies the body of the loop to a single
statement; we don't even need to use curly braces to produce a statement block.
The
for
loop supports some additional syntax that makes it even more convenient
to use. Because many loops use their loop variables only within the loop, the
for
loop allows the
initialize
expression to be a full variable declaration, so that the
variable is scoped to the body of the loop and is not visible outside of it. For
example:
for
(
int
count
=
0
;
count
<
10
;
count
++)
System
.
out
.
println
(
count
);
Furthermore, the
for
loop syntax does not restrict you to writing loops that use
only a single variable. Both the
initialize
and
update
expressions of a
for
loop
can use a comma to separate multiple initializations and update expressions. For
example:
for
(
int
i
=
0
,
j
=
10
;
i
<
10
;
i
++,
j
--)
sum
+=
i
*
j
;
Even though all the examples so far have counted numbers,
for
loops are not
restricted to loops that count numbers. For example, you might use a
for
loop to
iterate through the elements of a linked list:
for
(
Node
n
=
listHead
;
n
!=
null
;
n
=
n
.
nextNode
())
process
(
n
);
The
initialize
,
test
, and
update
expressions of a
for
loop are all optional; only
the semicolons that separate the expressions are required. If the
test
expression is
omitted, it is assumed to be
true
. Thus, you can write an infinite loop as
for(;;)
.
The foreach Statement
Java's
for
loop works well for primitive types, but it is needlessly clunky for han‐
dling collections of objects. Instead, an alternative syntax known as a
foreach
loop is
used for handling collections of objects that need to be looped over.
The foreach loop uses the keyword
for
followed by an opening parenthesis, a vari‐
able declaration (without initializer), a colon, an expression, a closing parenthesis,
and finally the statement (or block) that forms the body of the loop:
for
(
declaration
:
expression
)
statement
Despite its name, the foreach loop does not have a keyword
foreach
—instead, it is
common to read the colon as “in”—as in “foreach name in studentNames.”