In Java, the continue
statement is used within loops to skip the current iteration and proceed with the next one. It’s helpful when we want to bypass certain conditions while maintaining the loop’s overall execution.
Syntax of Continue
continue;
Continue in Loops
The continue
statement can be applied in different loops like for
, while
, and do-while
loops.
Example: Using Continue in a For Loop
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i equals 3
}
System.out.println(i);
}
Here, the loop will skip printing the number 3 and continue with the next iterations. The output will be:
1
2
4
5
Continue in While Loop
Similar to the for
loop, continue
can be used in a while
loop to skip specific iterations.
Example: Using Continue in While Loop
int i = 1;
while (i <= 5) {
if (i == 3) {
i++;
continue; // Skip the iteration when i equals 3
}
System.out.println(i);
i++;
}
This loop will also skip printing the number 3.
Continue in Nested Loops
When used in nested loops, the continue
statement only affects the loop in which it is placed.
Example: Using Continue in Nested Loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue; // Skip the iteration when j equals 2
}
System.out.println("i = " + i + ", j = " + j);
}
}
This will skip j = 2
for each value of i
.
Conclusion
The continue
statement offers precise control in loops by allowing certain conditions to be skipped while keeping the overall iteration process intact. It is ideal for skipping over unwanted iterations in both simple and nested loops. For more on Java’s control flow, check the official Java documentation.