Suppose you are working with loops. It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.
In such cases, break
and continue
statements are used. Visit this page to learn about break statement in Java.
The continue
statement skips the current iteration of a loop (for
, while
, and do...while
loop).
When continue
statement is executed, control of the program jumps to the end of the loop. Then, the test expression that controls the loop is evaluated. In case of for
loop, the update statement is executed before the test expression is evaluated.
It is almost always used with decision making statements (if...else Statement).
It's syntax is:
continue;
class Test {
public static void main(String[] args) {
for (int i = 1; i <= 10; ++i) {
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}
When the value of i becomes more than 4 and less than 9, continue
statement is exectued, which skips the execution of System.out.println(i);
statement.
When you run the program, the output will be:
1 2 3 4 9 10
The program below calculates the sum of maximum of 5 positive numbers entered by the user. If the user enters negative number or zero, it is skipped from calculation.
To take input from the user, Scanner
object is used. Visit Java Basic Input to learn more on how to take input from the user.
import java.util.Scanner;
class AssignmentOperator {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
for (int i = 1; i < 6; ++i) {
System.out.print("Enter a number: ");
number = input.nextDouble();
if (number <= 0.0) {
continue;
}
sum += number;
}
System.out.println("Sum = " + sum);
}
}
When you run the program, you will get similar output like this:
Enter a number: 2.2 Enter a number: 5.6 Enter a number: 0 Enter a number: -2.4 Enter a number: -3 Sum = 7.8
In case of nested loops, continue
skips the current iteration of innermost loop.
The continue
statement we have discussed till now is unlabeled form of continue
, which skips the execution of remaining statement(s) of innermost for
, while
and do..while
loop.
There is another form of continue
statement, labeled form, that can be used to skip the execution of statement(s) that lies inside the outer loop.
Here, label is an identifier.
class LabeledContinue {
public static void main(String[] args) {
label:
for (int i = 1; i < 6; ++i) {
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)
continue label;
System.out.println("i = " + i + "; j = " + j);
}
}
}
}
When you run the program, the output will be:
i = 1; j = 1 i = 2; j = 1 i = 4; j = 1 i = 5; j = 1
The use of labeled continue
is often discouraged as it makes your code hard to understand. If you are in a situation where you have to use labeled continue
, refactor your code and try to solve it in a different way to make it more readable.