The continue statement

The continue statement is used to skip the current iteration of a running loop. The continue statement is similar to the break statement but here, instead of terminating the loop, we simply skip the current iteration and continue with the next iteration.

Syntax

The syntax of the continue statement is very simple-

continue;

The continue statement can be used with any type of loop like – for loop, while loop, do while loop. The continue statement can be used in two different ways – 

  1. Simple continue statement
  2. Labeled continue statement

Simple continue statement

It is the simplest form of continue statement, it works only with the current loop scope. Following is the example of continue statement with for loop –

Example

public class ContinueExample {

    public static void main(String[] args) {

        for(int i = 0; i < 10; i++) {
            
            if (i == 5) {
                // Skip 5 and continue the loop
                continue;
            }

            System.out.println(i);
        }
    }

}

Explanation

In the above example program, one loop is started from 0 to 9, and inside the body of the loop, we are checking if the value of the variable (i) equals to 5 then skip the current iteration and continue with the next iteration. So whenever the condition i == 5 becomes true, the continue statement executes and it skips the current iteration.

Labeled continue statement

Just like labeled break statement, we can use the continue statement in the same fashion, means when we have nested looping and we want to target a particular loop to skip its current iteration we can use labeled continue statement. Following is the example of a labeled continue statement – 

Example

public class LabeledContinue {

    public static void main(String[] args) {

        outer:
        for(int i = 0; i < 4; i++) {
        
            inner:
            for(int j = 0; j < 4; j ++ ) {
                
                if (i == 2) {
                    // Break the outer loop
                    continue outer;
                }
                
                System.out.println("i = " + i + " j = " +j);

            }
        }
    }

}

Explanation

In the above example program, we have labeled the loop, the nested loop is labeled as inner: and the outer loop is labeled as outer: we will be using these labeling to identify and skip current iteration of the loop. Now in the nested loop, we are checking if the value of the variable (i) equals 2 then execute the continue statement but this time we are telling the continue statement to skip the current iteration of the given labeled loop, so instead of the current loop, it skips the current iteration of the outer loop.