Java Reference
In-Depth Information
An example of an unlabeled
continue
statement is
continue;
An example of a labeled
continue
statement is
continue label;
When a
continue
statement is executed inside a
for
loop, the rest of the statements in the body of the loop are
skipped and the expressions in the expression-list are executed. You can print all odd integers between 1 and 10 using
a
for
-loop statement, as shown:
for (int i = 1; i < 10; i += 2) {
System.out.println(i);
}
In this
for
-loop statement, you increment the value of
i
by 2 in the expression-list. You can rewrite the above
for
-loop statement using a
continue
statement, as shown in Figure
5-3
.
Figure 5-3.
Using a continue statement inside a for-loop statement
The expression
i % 2
returns zero for the values of
i
that are multiple of 2, and the expression
i % 2 == 0
returns
true
. In such cases, the
continue
statement is executed and the last statement,
System.out.println(i)
, is skipped.
The increment statement
i++
is executed after the
continue
statement is executed. The above snippet of code is
certainly not the best example of using a
continue
statement; however, it serves the purpose of illustrating its use.
When an unlabeled
continue
statement is executed inside a
while
loop or
do-while
loop, the rest of the statements
in the loop is skipped and the condition-expression is evaluated for the next iteration. For example, the snippet of code
in Figure
5-4
will print all odd integers between 1 and 10, using a
continue
statement inside a
while
loop.
Figure 5-4.
Using a continue statement inside a while-loop statement