Continue statement in java

Let’s learn continue statement in java.

Continue statement in java

Continue statement jumps to next iteration of a loop based on specific condition. Continue statement in java is used in many loop control structures.

Continue keyword can be used with the loops namely, for loop and do while loop.

Syntax

continue;

continue in java example

import java.util.*;
public class ContinueJavaExample 
{
   public static void main(String[] args) 
   {
      for(int a = 1; a <= 10; a++)
      {
         if(a % 2 != 0)
         {
            continue;
         }
         System.out.println(a + " ");
      }
   }
}


Output:

2
4
6
8
10


continue in while loop java

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 label example or java continue label

Java continue label skips current iteration of outer loop. Here’s the java continue label example.

public class ContinueLabelExample 
{
   public static void main(String[] args) 
   {
      outer: for(int a = 0; a < 5; a++)
      {
         System.out.println("\n" + "a : " + a + "\n");
         for(int b = 0; b < 6; b++)
         {
            if(b == 2)
            {
               continue outer;
            }
            System.out.println("b : " + b);
         }
      }
   }
}


Output:

a : 0

b : 0
b : 1

a : 1

b : 0
b : 1

a : 2

b : 0
b : 1

a : 3

b : 0
b : 1

a : 4

b : 0
b : 1


break statement in java or break in java

If break statement is encountered in a loop, that loop will terminate and the control will shift to next statement of the same loop.

Syntax:

break;

break statement is used to terminate case in switch case statement in java.

Java break statement is also used in all types of loops such as while loop, do-while loop and for loop.

Let’s see an example on break statement in java.

public class BreakStatementExample
{
   public static void main(String[] args) 
   {
      for(int a = 1; a <= 10; a++)
      {
         if(a == 3)
         {  
            // breaking loop  
            break;  
         }  
         System.out.println(a);  
      }
   }
}


Output:

1
2