The continue Statement


Sometimes it is useful to force an early iteration of a loop. That is to say that you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:
 for ( int i = 0; i < 10; i++ ) {
   if ( i == 4 )  continue;
   System.out.print( i );
 }     // Output: 012356789

This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.

ContinueDemo.java (the continue statement)
// Using continue in an if statement
class ContinueDemo { 
  public static void main( String args[ ] ) {
    int j = Integer.parseInt( args[0] ); 
    for ( int i = 0; i < j; i++ ) { 
      // If the number is even, skip and continue.
      if ( i%2 == 0 ) continue; 
      // If number is odd, print it. 
      System.out.print( i + " " ); 
    } 
  } 
}
shell> java ContinueDemo  

Output:      

BreakContinue.java (break and continue keywords)
public class BreakContinue {
  public static void  main( String args[ ] ) {
    int i = 0, j = 0;
    int k = Integer.parseInt( args[0] );
    while ( i++ < 10 ) {
      for ( j = 0; j < 10; j++ )
        if ( j == k ) break;
        else continue;
      if ( i == j ) break;
      else continue;
    }
    System.out.print( i );
  }
}
shell> java BreakContinue  

Output:           Result: