Java Continue Statement in Loops

(Last Updated On: February 26, 2019)

Learn how to use continue statements in java programming with loops.  Java code examples using continue statement with for loop, while loop, do while etc are provide.

We have learned the break statement in java to break the loop. now We’ll learn continue statement inside a loop to skip some of the code for some specific condition and keep the loop running.

Prerequisite:

 

Continue Statement in Java Programming

Continue statement is used inside a loop, if we want to skip some of the code in the loop based on some condition while loop is running.

For example, in below for loop, that will run for 5 times, we don’t want to execute lines 1 and 2 inside the loop, when loop is running second time.

 

In simple words,

  • Loop is running 5 times.
  • when the value of variable i is equal to 2, then, we don’t want to run line-2 and line-3.
  • for rest of the value of i, except 2, all line-1, line-2 and line-3 should be executed.

So, as a solution, we can use continue statement in the loop with condition if( I ==2), as shown below in the code.

 

As soon as continue is encountered on meeting the condition in if block, the control will come back on start of the loop skipping line-2 and line-3. Again when value of variable I goes to 3,4 or 5 etc all lines i.e.line-1, line-22 and line-3 will be executed.

 

Continue in for loop in java

In below java code example, the loop will not execute the line System.out.println(i); when value of variable i is equal to 2.

Output:
1
3
4
5

 

Continue in while loop

In below program as soon as continue is encountered on meeting the condition in if block, the control will come back on start of the loop and run.

For example, in below program, the while loop is running 5 times, but, when it meets the condition (i == 2) in if block then continue will be encountered and control will go back to start of the while loop and run again for the value of i=3.

Make a focus that when continue execute, the System.out.println(i); statement will be skipped and not be executed. Again, when loop runs for value of 3,4, then print statement will execute.

So, output will be as below. value 2 will be skipped as continue went on start of the loop skipping the print statement.

Output:
1
3
4
5

 

Continue statement in do while loop

Same concept as for while loop. Outputting
1
3
4
5