Java Reference
In-Depth Information
The three expressions at the start of a
for
statement are separated by two, and only
two, semicolons. Do not succumb to the temptation to place a semicolon after the
third expression. (The technical explanation is that these three things are expressions,
not statements, and so do not require a semicolon at the end.)
A
for
statement often uses a single
int
variable to control loop iteration and loop
ending. However, the three expressions at the start of a
for
statement may be any Java
expressions and therefore may involve more (or even fewer) than one variable, and the
variables can be of any type.
The semantics of the
for
statement are given in Display 3.9. The syntax for a
for
statement is given in Display 3.10. Display 3.10 also explains how the
for
statement
can be viewed as a notational variant of the
while
loop.
The
for
Statement
SYNTAX
for
(
Initialization
;
Boolean_Expression
;
Update
)
Body
The
Body
may be any Java statement—either a simple statement or, more likely, a compound
statement consisting of a list of statements enclosed in braces,
{}
. Notice that the three things
in parentheses are separated by two, not three, semicolons.
You are allowed to use any Java expression for the
Initializing
and the
Update
expressions.
Therefore, you may use more, or fewer, than one variable in the expressions; moreover, the
variables may be of any type.
EXAMPLE
int
next, sum = 0;
for
(next = 0; next <= 10; next++)
{
sum = sum + next;
System.out.println("sum up to " + next + " is " + sum);
}
A variable can be declared in the heading of a
for
statement at the same time that it
is initialized. For example:
for
(
int
n = 1; n < 10; n++)
System.out.println(n);
There are some subtleties to worry about when you declare a variable in the heading of
a
for
statement. These subtleties are discussed in Chapter 4 in the Programming Tip
subsection entitled “Declaring Variables in a
for
Statement.” It might be wise to avoid
such declarations within a
for
statement until you reach Chapter 4, but we mention it
here for reference value.