Java Reference
In-Depth Information
TIP: Repeat
N
Times Loops
The simplest way to produce a loop that repeats the loop body a predetermined num-
ber of times is with a
for
statement. For example, the following is a loop that repeats
its loop body three times:
for
(
int
count = 1; count <= 3; count++)
System.out.println("Hip, Hip, Hurray");
The body of a
for
statement need not make any reference to a loop control variable,
such as the variable
count
.
■
PITFALL: Extra Semicolon in a
for
Statement
You normally do not place a semicolon after the closing parenthesis at the beginning
of a
for
loop. To see what can happen, consider the following
for
loop:
Problem
semicolon
for
(
int
count = 1; count <= 10; count++);
System.out.println("Hello");
If you did not notice the extra semicolon, you might expect this
for
loop to write
Hello
to the screen 10 times. If you do notice the semicolon, you might expect the
compiler to issue an error message. Neither of those things happens. If you embed this
for
loop in a complete program, the compiler will not complain. If you run the pro-
gram, only one
Hello
will be output instead of 10 Hellos. What is happening? To
answer that question, we need a little background.
One way to create a statement in Java is to put a semicolon after something. If you
put a semicolon after
number++
, you change the expression
number++
into the statement
number++;
If you place a semicolon after nothing, you still create a statement. Thus, the
semicolon by itself is a statement, which is called the
empty statement
or the
null
statement
. The empty statement performs no action, but still is a statement. There-
fore, the following is a complete and legitimate
for
loop, whose body is the empty
statement:
empty
statement
null
statement
for
(
int
count = 1; count <= 10; count++);
(continued)