Continue statement in java

Let’s learn continue statement in java.

Continue statement in java

Continue keyword in java is used in many loop control structures. Use of continue statement is, it will skip a particular iteration and moves to next iteration.

Also read – treemap in java

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

Syntax

continue;

Flow diagram:

continue statement in java

Continue in nested for loop java

In nested for loop if continue statement is encountered, it jumps to very next inner loop. Meanwhile to jump current iteration of outer loop label can be used.

Now let’s see java continue for loop. In the below java program we can use continue statement to skip one number, i.e, 6 of all numbers from 1 to 10.

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



Output:

1
2
3
4
5
7
8
9
10


Java continue in while loop

In the below java continue while loop, numbers from 1 to 10 are printed except 4.

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



Output:

1
2
3
5
6
7
8
9
10


Java continue in do while loop

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

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



Output:

1
2
3
4
5
6
8
9
10

Java continue label example

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