Java Reference
In-Depth Information
The continue Statement
There are situations where you may want to skip all or part of a loop iteration. Suppose we want to sum
the values of the integers from 1 to some limit, except that we don't want to include integers that are
multiples of three. We can do this using an if and a continue statement:
for(int i = 1; i <= limit; i++) {
if(i % 3 == 0) {
continue; // Skip the rest of this iteration
}
sum += i; // Add the current value of i to sum
}
The continue statement is executed in this example when i is an exact multiple of 3, causing the rest of the
current loop iteration to be skipped. Program execution continues with the next iteration if there is one, and if
not, with the statement following the end of the loop block. The continue statement can appear anywhere
within a block of loop statements. You may even have more than one continue in a loop.
The Labeled continue Statement
Where you have nested loops, there is a special form of the continue statement that enables you to
stop executing the inner loop - not just the current iteration of the inner loop - and continue at the
beginning of the next iteration of the outer loop that immediately encloses the current loop. This is
called the labeled continue statement .
To use the labeled continue statement, you need to identify the loop statement for the enclosing outer loop
with a statement label . A statement label is simply an identifier that is used to reference a particular
statement. When you need to reference a particular statement, you write the statement label at the beginning
of the statement in question, and separated from the statement by a colon. Let's look at an example:
Try It Out - Labeled continue
We could add a labeled continue statement to omit the calculation of factorials of odd numbers
greater than 10. This is not the best way to do this, but it does demonstrate how the labeled continue
statement works:
public class Factorial {
public static void main(String[] args) {
long limit = 20; // to calculate factorial of integers up to this value
long factorial = 1; // factorial will be calculated in this variable
// Loop from 1 to the value of limit
OuterLoop:
for(int i = 1; i <= limit; i++) {
factorial = 1; // Initialize factorial
for(int j = 2; j <= i; j++) {
if(i > 10 && i % 2 == 1) {
continue OuterLoop; // Transfer to the outer loop
}
factorial *= j;
}
Search WWH ::




Custom Search