continue Statement

In Java, the continue statement is used within loops (such as for, while, or do-while) to skip the current iteration and move on to the next iteration of the loop. It is often used when you want to skip a particular iteration based on some condition, but you don’t want to exit the loop entirely.

Here’s the syntax for the continue statement in Java:

continue;Code language: JavaScript (javascript)

Here’s a simple example program that demonstrates the use of the continue statement within a for loop. This program prints all even numbers from 1 to 10:

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            // Check if the current number is odd. If it is, skip this iteration.
            if (i % 2 != 0) {
                continue;
            }
            // Print even numbers
            System.out.println(i);
        }
    }
}

In this example:

  1. We initialize a for loop with a loop variable i ranging from 1 to 10.
  2. Inside the loop, we use the if statement to check if the current value of i is odd (i.e., not divisible by 2).
  3. If i is odd, the continue statement is executed, which causes the loop to skip the rest of the code within the loop for the current iteration.
  4. If i is even, the System.out.println(i) statement is executed, and the even number is printed.
  5. The loop then proceeds to the next iteration, repeating the process until i reaches 10, and all even numbers between 1 and 10 are printed.

When you run this program, you will see the following output:

2

4

6

8

10

As you can see, the continue statement is used to skip the odd numbers and only print the even numbers within the specified range. 

Scroll to Top