Java Reference
In-Depth Information
7
int
count;
// control variable also used after loop terminates
8
9
for
(count =
1
; count <=
10
; count++)
// loop 10 times
10
{
11
if
(count ==
5
)
12
break
;
// terminates loop if count is 5
13
14
System.out.printf(
"%d "
, count);
15
}
16
17
System.out.printf(
"%nBroke out of loop at count = %d%n"
, count);
18
}
19
}
// end class BreakTest
1 2 3 4
Broke out of loop at count = 5
Fig. 5.13
|
break
statement exiting a
for
statement. (Part 2 of 2.)
When the
if
statement nested at lines 11-12 in the
for
statement (lines 9-15) detects
that
count
is
5
, the
break
statement at line 12 executes. This terminates the
for
statement,
and the program proceeds to line 17 (immediately after the
for
statement), which displays
a message indicating the value of the control variable when the loop terminated. The loop
fully executes its body only four times instead of 10.
continue
Statement
The
continue
statement, when executed in a
while
,
for
or
do
…
while
, skips the remain-
ing statements in the loop body and proceeds with the
next iteration
of the loop. In
while
and
do
…
while
statements, the program evaluates the loop-continuation test immediately
after the
continue
statement executes. In a
for
statement, the increment expression exe-
cutes, then the program evaluates the loop-continuation test.
1
// Fig. 5.14: ContinueTest.java
2
// continue statement terminating an iteration of a for statement.
3
public class
ContinueTest
4
{
5
public static void
main(String[] args)
6
{
7
for
(
int
count =
1
; count <=
10
; count++)
// loop 10 times
8
{
9
if
(count ==
5
)
10
continue
;
// skip remaining code in loop body if count is 5
11
12
System.out.printf(
"%d "
, count);
13
}
14
15
System.out.printf(
"%nUsed continue to skip printing 5%n"
);
16
}
17
}
// end class ContinueTest
Fig. 5.14
|
continue
statement terminating an iteration of a
for
statement. (Part 1 of 2.)