.

The break and continue Statement

Using break statement : When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:

/**
 * This program demonstrates
 * break to exit a loop.
 */
public class BreakDemo
{
   public static void main(String[] args)
   {
      for (int i = 1; i <= 10; i++)
      {
         if (i == 5)
         {
            break;    // terminate loop if i is 5
         }

         System.out.print(i + " ");
      }

      System.out.println("Loop is over.");
   }
}

Output :

1 2 3 4 Loop is over.

 

Using continue statement : When a continue statement is encountered inside the body of a loop, remaining statements are skipped and loop proceeds with the next iteration. Here is a simple example.

/**
 * This program demonstrates continue
 * to skip remaining statements of iteration.
 */
public class ContinueDemo
{
   public static void main(String[] args)
   {
      for (int i = 1; i <= 10; i++)
      {
         if (i % 2 == 0)
         {
            continue;    // skip next statement if i is even
         }

         System.out.println(i + " ");
      }
   }
}

Output :

1 3 5 7 9