Continue statement in Java

There are situations when you want to avoid rest of the statements inside the loop but you still want to continue running the loop. In those cases continue statement is quite useful. Like in the example below only odd numbers are printed:

The output is :

Example works like this:

  • If i is even then it skips rest of the statements inside the for loop and sends the control to the iteration section of the loop which increments the i. So print statement is not executed.
  • If i is odd then normal execution path follows and print statement is executed.

Variations in Control Flow

Continue statement works only inside loops. It cannot be used with blocks or nested blocks of code. Even with loops the control flow is little different in case of for and while loop:

  • In while and do-while loops, a continue statement sends the control to the conditional expression that control the loop.
  • In for and for-each loop, a continue statement sends the control first to the iteration section and then to the conditional expression that controls the loop.

Here is the same example with while loop:

It produces exactly same output:

Here is the same example with do while loop:

It also produces exactly same output:

 

 


Using continue with inner loops

In case of nested loops, when continue is used inside the inner loop, it only afects the continuation of inner loop, the outer loop is left unaffected.

The output is:

 


Using continue with labels

Using continue, you can goto any labeled loop that encloses this continue. Using single continue, you can go to the start of a series of nested loops. The syntax is   continue label

To label a loop, you have to put any valid Java identifier name followed by a colon before the loop.

The output is a triangular matrix:

In the example. the outer loop is labeled first. As soon as j becomes as large as i, continue sends the control back to the outer loop. Also note that initialization of i in the outer loop is done only once.


Continue has no other significant use other than those shown above.