Java Reference
In-Depth Information
This, in effect, makes the loop body part of the update action. We find that it makes for a
more readable style if you use the update action only for variables that control the loop, as
in the previous version of this
for
loop. We do not advocate using
for
loops with no body,
but if you do use a
for
loop with no body, annotate it with a comment such as we did in
the preceding
for
loop. As indicated in the upcoming Pitfall, “Extra Semicolon in a
for
Statement,” a
for
loop with no body can also occur as the result of a programmer error.
The comma used in a
for
statement, as we just illustrated, is quite limited in how it
can be used. You can use it with assignment statements and with incremented and dec-
remented variables (such as
term++
or
term--
), but not with just any arbitrary state-
ments. In particular, both declaring variables and using the comma in
for
statements
can be troublesome. For example, the following is illegal:
for
(
int
term = 1,
double
sum = 0; term <= 10; term++)
sum = sum + term;
Even the following is illegal:
double
sum;
for
(
int
term = 1, sum = 0; term <= 10; term++)
sum = sum + term;
Java will interpret
int
term = 1, sum = 0;
as declaring both
term
and
sum
to be
int
variables and complain that
sum
is already
declared.
If you do not declare
sum
anyplace else (and it is acceptable to make
sum
an
int
vari-
able instead of a
double
variable), then the following, although we discourage it, is legal:
for
(
int
term = 1, sum = 0; term <= 10; term++)
sum = sum + term;
The first part in parentheses (up to the semicolon) declares both
term
and
sum
to be
int
variables and initializes both of them.
It is best to simply avoid these possibly confusing examples. When using the comma
in a
for
statement, it is safest to simply declare all variables outside the
for
statement. If
you declare all variables outside the
for
loop, the rules are no longer complicated.
A
for
loop can have only one Boolean expression to test for ending the
for
loop.
However, you can perform multiple tests by connecting the tests using
&&
or
||
oper-
ators to form one larger Boolean expression.
(C, C++, and some other programming languages have a general-purpose comma oper-
ator. Readers who have programmed in one of these languages need to be warned that, in
Java, there is no comma operator. In Java, the comma is a separator, not an operator, and its
use is very restricted compared with the comma operator in C and C++.)