The continue statement is a control statement that is used to skip the following statement in the body of the loop and continue with the next iteration of the loop.
Types of continue statement:
- Unlabeled continue statement: is used to skip the following statement in the body of the loop when a specific condition returns true.
- Labeled continue Statement: This is used to skip the following statement in the body of the specific loop based on the label when the specific condition returns true.
Syntax of Unlabeled continue statement:
for( initialization; condition; statement){
//Block of statements
if(condition){
continue;
}
}
Program to use for loop Continue example in Java.
/**
* Program to use for loop Continue example in java.
* @author W3schools360
*/
public class ForLoopContinueExample {
static void forLoopContinueTest(int num){
//For loop test
for(int i=1; i<= num; i++){
if(i==6){
//Continue the execution of for loop.
continue;
}
System.out.println(i);
}
}
public static void main(String args[]){
//method call
forLoopContinueTest(10);
}
}
Output
1 2 3 4 5 7 8 9 10
Syntax of Labeled continue statement
Label1:
for( initialization; condition; statement){
Label2:
for( initialization; condition; statement){
//Block of statements
if(condition){
continue Label1;
}
}
}
Program to use for loop Continue label example in Java.
/**
* Program to use for loop Continue label example in java.
* @author W3schools360
*/
public class ForLoopContinueLabelExample {
static void forLoopContinueLabelTest(int num1, int num2){
//For loop continue label test
Outer:
for(int i=1; i<= num1; i++){
Inner:
for(int j=1; j<= num2; j++){
if(i + j == 4){
//Continue the execution of Outer for loop.
continue Outer;
}
System.out.println(i + j);
}
}
}
public static void main(String args[]){
//method call
forLoopContinueLabelTest(3, 2);
}
}
Output
2 3 3