Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

control structure
skip
while
for
java

How to use a continue statement in Java loops

Educative Answers Team

The continue statement is an intentional interrupt used to skip one iteration of the loop when a condition inside the loop is satisfied.

Similar to a break statement, where the loop breaks and the program moves on to the code block after the loop, the continue statement moves to the next iteration of the loop with the updated values of variables, if there are any.

Let’s have a look at how the continue statement works:

svg viewer
How a `continue` statements works in a loop

Examples

Now that we know how the continue statement works in theory, let’s see how it works in the actual code.

We will look at both examples: How it can be used in a for loop and in a while loop.

1. For Loop

class ForLoopContinue {
    public static void main(String args[]) {
        char [] alphabets = {'a', 'b', 'c', 'd', 'e'};

        for(char x : alphabets) {
            if(x == 'c') {
                continue;
            }
            System.out.print(x);
            System.out.print("\n");
        }
    }
}
The loop skips the the iteration (does not print the value) when value is character 'c'

2. While Loop

class WhileLoopContinue {
    public static void main(String args[]) {
        int [] nums = {98, 31, 45, 155, 32, 76};
        int i = 0;

        while(i < nums.length) {
            i++;
            if(nums[i-1] < 45) {
                continue;
            }
            System.out.print(nums[i-1]);
            System.out.print("\n");
        }
    }
}
The loop skips the the iteration (does not print the value) when value is less than 45

RELATED TAGS

control structure
skip
while
for
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring