The break and continue statements

  • The break and continue statements give you additional control over the execution of a loop statement

  • break:

      • Terminates the loop immediately

        The program will continue at the statement after the loop

  • continue:

      • Starts the next iteration immediately

        The rest of the loop body is skipped

Example showing the effect of the break statement

When i == 4, the program will execute the break statement and terminates the loop immediately:

   public static void main(String[] args) 
   {
      int i;

      for ( i = 0; i < 10; i++ )   // i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
      {
          if ( i == 4 )
              break;               // Terminate the loop
              
          System.out.println(i);
      }

      System.out.println("Done");
   } 
  

Prints out: 0, 1, 2, 3, Done

DEMO: demo/05-loops/07-break+cont/Break.java

Example showing the effect of the continue statement

When i == 4, the program will execute the continue statement and skip the remainder of the loop body:

   public static void main(String[] args) 
   {
      int i;

      for ( i = 0; i < 10; i++ )   // i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
      {
          if ( i == 4 )
              continue;            // Skip the remainder of the loop body
              
          System.out.println(i);
      }

      System.out.println("Done");
   } 
  

Prints out: 0, 1, 2, 3, 5, 6, 7, 8, 9 Done       (4 is missing !)

DEMO: demo/05-loops/07-break+cont/Continue.java