The continue Statement in Loops
What you'll learn: How to use continue to skip the rest of the current loop iteration and immediately jump to the next one.
What Does continue Do?
The continue statement tells Java to skip everything remaining in the current iteration of a loop and jump straight to the next iteration. Unlike break, which exits the loop entirely, continue just skips ahead within the same loop.
Think of it like skipping a song on a playlist—you don't stop listening to music altogether, you just move to the next track.
How It Works
When Java encounters continue:
- In a
whileordo-whileloop, it jumps back to the condition check - In a
forloop, it jumps to the update expression, then checks the condition - The rest of the code in that iteration is completely bypassed
Basic Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip when i is 3
}
System.out.println(i);
}
// Output: 1, 2, 4, 5 (3 is skipped)
Common Use Case: Filtering
int count = 0;
while (count < 10) {
count++;
if (count % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(count); // Only prints odd numbers
}
Here, when count is even, continue causes the println to be skipped, and the loop moves to the next iteration.
Key Takeaway: The continue statement skips the remaining code in the current loop iteration and proceeds directly to the next iteration, making it perfect for filtering or conditional processing within loops.