Java continue statement

Let’s learn java continue statement.

Java continue statement

If continue statement is encountered within a loop then the current iteration is skipped and continued for next iteration.

We can use continue statement only inside loops namely for loop, while loop and do while loop.

Syntax

continue;


Java continue inside for loop

public class ContinueJavaExample 
{
   public static void main(String[] args) 
   {
      for(int a = 1; a <= 10; a++)
      {
         if(a == 5)
         {
            continue;
         }
         System.out.println(a + " ");
      }
   }
}

Output:

1
2
3
4
6
7
8
9
10


Java continue in while loop

In the below while loop, we are iterating numbers from 10 to 0 are printed except 3 using continue statement.

public class ContinueWhileDemo
{
   public static void main(String[] args)
   {
      int number = 10;
      while(number >= 0)
      {
         if(number == 3)
         {
            number--;
            continue;
         }
         System.out.print(number + " ");
         number--;
      }
   }
}

Output:

10 9 8 7 6 5 4 2 1 0


Java continue in do while loop

Similar to above java program we can replace with do while loop. Here the java program.

public class ContinueDoWhile
{
   public static void main(String[] args)
   {
      int a = 0;
      do
      {
         if(a == 4)
         {
            // continue statement
            a++;
            continue;
         }
         System.out.println(a + " ");
         a++;
      }while(a <= 10);
   }
}

Output:

0 1 2 3 5 6 7 8 9


Java continue inside inner loop or nested loop

Java continue statement skips execution when a == 3 && b == 4 in inner for loop. Here’s the continue inside inner loop or nested loop example.

public class ContinueNestedLoopExample 
{
   public static void main(String[] args) 
   {
      // outer loop for iteration
      for(int a = 1; a <= 7; a++)
      {
         // inner loop for iteration
         for(int b = 1; b <= 3; b++)
         {
            if(a == 3 && b == 4)
            {
               // skip execution when a == 3 and b == 4
               continue;
            }
            System.out.println(a + " * " + b);
         }
      }
   }
}

Output:

1 * 1
1 * 2
1 * 3
2 * 1
2 * 2
2 * 3
3 * 1
3 * 2
3 * 3
4 * 1
4 * 2
4 * 3
5 * 1
5 * 2
5 * 3
6 * 1
6 * 2
6 * 3
7 * 1
7 * 2
7 * 3


Also read – major features of java