The continue statement is used in loop control structures when you need to immediately jump to the next iteration of the loop. It can be used with either a for loop or a while loop.
To continue the loop, the Java continue statement is used. It continues the program's current flow while skipping the remaining code at the specified condition. In the case of an inner loop, it only continues the inner loop.
In programming languages, the continue statement is frequently used inside loop control structures. When a continue statement is encountered within the loop, the control jumps directly to the beginning of the loop for the next iteration rather than executing the statements of the current iteration. When we want to skip a specific condition and continue with the rest of the execution of program then we use the continue statement. The Java continue statement can be used in any type of loop, but it is most commonly found in for, while, and do-while loops.
Syntax
continue;
When a loop encounters a continue statement, that iteration is skip in loop
// continue statement using for loop
public class Student { public static void main(String[] args) { for (int i = 1; i < 10; i++) { if (i == 5){ System.out.println(); // this print statement to just show skip value continue; // use continue keyword to skip the current iteration } System.out.println(i); } } }
Output:
1
2
3
4
5
6
7
8
9
// continue statement with labeled for loop. we use return instead of continue
import java.util.Arrays; import java.util.List; public class Student { public static void main(String[] args) { List<Integer> numberList = Arrays.asList(20,31,41,50,69,80); numberList.forEach( x-> { if( x%2 == 0) { return; // only skips this iteration. } System.out.println(x); }); } }
Output:
31
41
69
// continue statement with while loop
public class Student { public static void main(String[] args) { int i=1; while(i<=5){ if(i==4){ i++; continue; } System.out.println(i); i++; } } }
Output:
1
2
3
5
// continue statement with do.. while loop
public class Student{ public static void main(String[] args){ int i=1; do { if(i==4){ i++; continue; } System.out.println(i); i++; } while (i<=5); } }
Output:
1
2
3
5
Post your comment