Java

Continue Statement In Java

Most often, continue statements are employed inside of loops. When it occurs inside a loop, the control immediately jumps to the beginning of the loop for the following iteration, bypassing the execution of statements inside the body of the loop for the current iteration. This is very helpful when you want to keep running the loop but don’t want the lines that follow the continue statement in the loop body to run during that iteration.

Continued word is followed by a semicolon in syntax.

continue;

Example: continue statement inside for loop

public class ContinueExample {

   public static void main(String args[]){
	for (int j=0; j<=6; j++)
	{
           if (j==4)
           {
	      continue;
	   }

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

Output:

0 1 2 3 5 6

Example: Use of continue in While loop

The same thing is seen here. When the counter value reaches 7, the loop skips the print statement and moves on to the next iteration of the while loop. We are iterating this loop from 10 to 0 for counter value.

public class ContinueExample2 {

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

Output:

10 9 8 6 5 4 3 2 1 0

Example of continue in do-While loop

public class ContinueExample3 {

   public static void main(String args[]){
	int j=0;
        do
	{
	   if (j==7)
	   {
		 j++;
		 continue;
	   }
	   System.out.print(j+ " ");
	   j++;
       }while(j<10);
		  
   }
}

Output:

0 1 2 3 4 5 6 8 9

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button