Core Java Fundamentals ยท Loops

Continue Statement

Learn how to use the "continue" statement to skip the current iteration of a loop and proceed to the next one.

ContinueExample.java

public class ContinueExample {
    public static void main(String[] args) {
        System.out.println("Printing odd numbers from 1 to 5:");
        for (int i = 1; i <= 10; i++) {
            // Check if the number is even
            if (i % 2 == 0) {
                // If it's even, skip the rest of the loop body
                continue;
            }
            // This line is skipped for even numbers
            System.out.println("Number: " + i);
        }
        System.out.println("Loop finished.");
    }
}

Step by step

  1. The program starts by printing an introductory message to the console.
  2. A for loop is initialized. A new variable i is created in the stack with the value 1. The loop will run as long as i is less than or equal to 10.
  3. Iteration 1: i is 1. The condition i % 2 == 0 (1 % 2 == 0) is false.
  4. Since the condition was false, the continue statement is skipped. The program prints the current value of i.
  5. End of iteration 1. The loop updates i to 2 (i++). The loop condition 2 <= 10 is true, so a new iteration begins.
  6. Iteration 2: i is 2. The condition i % 2 == 0 (2 % 2 == 0) is true.
  7. The continue statement is executed. This immediately skips the rest of the code in this iteration (line 11) and jumps to the update part of the loop (i++).
  8. End of iteration 2. The loop updates i to 3. The loop condition 3 <= 10 is true.
  9. Iteration 3: i is 3. The condition i % 2 == 0 (3 % 2 == 0) is false.
  10. The program prints the current value of i, which is 3.
  11. The loop continues this pattern, skipping even numbers and printing odd numbers.
  12. The loop condition 5 <= 5 is true, so the loop continues.
  13. Iteration 4: i is 5. The condition i % 2 == 0 (5 % 2 == 0) is false.
  14. The program prints the current value of i, which is 5.
  15. The program executes the final print statement after the loop has finished.