Continue java example

Welcome to flower brackets blog. In this post you are going to learn continue java example.

continue java example

In java, continue is a control statement. This continue keyword is normally used in many loop control structures.

Also read – java constructor example

Syntax

continue;

What is the function of continue in java?

Continue statement causes loop to immediately jump to next iteration of the loop. Hence skipping statements inside loop. Let’s see an example,

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

Output:

1
2
3
4
5
7
8
9
10


Inner loop continue statement

Inner for loop continues if we use continue statement. Here’s the code,

public class ContinueDemo 
{
   public static void main(String[] args) 
   {
      // outer for loop 
      for(int a = 5; a <= 7; a++)
      { 
         // inner for loop 
         for(int b = 5; b <= 7; b++)
         { 
            if(a == 6 && b == 6)
            { 
               // using continue statement inside loop 
               continue; 
            } 
            System.out.println(a + " " + b); 
         }
      }
   }
}

Output:

5 5
5 6
5 7
6 5
6 7
7 5
7 6
7 7


Labeled for loop continue statement

From JDK 1.5 java introduced new feature where continue statement can be used with label. This label can be applied to inner loop or outer loop.

public class ContinueStatement
{
   public static void main(String[] args)
   {
      aa: 
      for(int x = 5; x <= 7; x++)
      { 
         bb: 
         for(int y = 5; y <= 7; y++)
         { 
            if(x == 6 && y == 6)
            { 
               // using continue statement with label 
               continue aa; 
            } 
            System.out.println(x + " " + y); 
         } 
      }
   }
}

Output:

5 5
5 6
5 7
6 5
7 5
7 6
7 7


While loop continue statement

Here continue statement is used inside a while loop,

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


Do-while loop continue statement

We can also see the use of continue statement in do while loop in java.

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


Related Posts