Core Java Fundamentals ยท Loops
Learn how to use the "continue" statement to skip the current iteration of a loop and proceed to the next one.
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.");
}
}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.i is 1. The condition i % 2 == 0 (1 % 2 == 0) is false.continue statement is skipped. The program prints the current value of i.i to 2 (i++). The loop condition 2 <= 10 is true, so a new iteration begins.i is 2. The condition i % 2 == 0 (2 % 2 == 0) is true.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++).i to 3. The loop condition 3 <= 10 is true.i is 3. The condition i % 2 == 0 (3 % 2 == 0) is false.i, which is 3.5 <= 5 is true, so the loop continues.i is 5. The condition i % 2 == 0 (5 % 2 == 0) is false.i, which is 5.