To restart a loop iteration, we can use continue statement.
The continue statement stops the remainder of the code in the loop body for this particular iteration.
In do..while and while loop the continue statement transfers to the conditional expression that controls the loop.
In a for loop, control goes first to the iteration part of the for statement and then condition part.
Here is an example program that uses continue to cause two numbers to be printed on each line:
public class Main { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0){ continue; }/* w w w . java 2 s . c om*/ System.out.println(""); } } }
This code uses the %
operator to check if i
is even.
Java continue statement can have a label.
Here is an example program that uses continue to print a triangular multiplication table for 0 through 9:
// Using continue with a label. public class Main { public static void main(String args[]) { outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j > i) { System.out.println(); continue outer; }/* w w w . j ava 2 s .c om*/ System.out.print(" " + (i * j)); } } System.out.println(); } }