Java Continue Statement
Examples and Detailed Explanation
In Java, the continue
statement is used to skip the current iteration of a loop and move to the next iteration. It does not terminate the loop entirely (unlike break
) — instead, it simply jumps over the remaining statements inside the loop body for that iteration.
When Should You Use continue
?
You use continue
when you want to ignore specific cases inside loops but still allow the loop to run. It's especially helpful when filtering data, skipping invalid inputs, or jumping over certain conditions without cluttering your loop logic.
Syntax of continue
in Java
continue;
It’s that simple — just the word continue
followed by a semicolon. Let’s bring it to life with examples.
Example 1: Skipping Even Numbers
public class ContinueExample1 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("Odd number: " + i);
}
}
}
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Explanation
Here, we loop from 1 to 10. When the number is even, the continue
statement is triggered — the print statement is skipped, and the loop moves to the next number.
Example 2: Using continue
in a While Loop
public class ContinueExample2 {
public static void main(String[] args) {
int i = 0;
while (i < 6) {
i++;
if (i == 3) {
continue;
}
System.out.println("i = " + i);
}
}
}
i = 1
i = 2
i = 4
i = 5
i = 6
Explanation
When i == 3
, the continue
skips the System.out.println()
and moves directly to the next loop cycle. That's why 3 is missing in the output.
Example 3: continue
with Do-While Loop
public class ContinueExample3 {
public static void main(String[] args) {
int i = 0;
do {
i++;
if (i == 2 || i == 4) {
continue;
}
System.out.println("Value: " + i);
} while (i < 5);
}
}
Value: 1
Value: 3
Value: 5
Explanation
This example shows that continue
also works inside do-while
loops. Notice how 2 and 4 are skipped.
Common Use Cases
- Skip invalid or unwanted values in a list or array
- Ignore specific characters in a string processing loop
- Prevent certain cases from being logged or printed
Points to Remember
continue
skips only the current iteration, not the entire loop.- It's useful in all loop types —
for
,while
, anddo-while
. - Use it to simplify logic by avoiding nested
if-else
structures.
Quick Comparison: continue
vs break
Keyword | Effect | Use Case |
---|---|---|
continue |
Skips current loop iteration | Filter or ignore certain values |
break |
Exits the loop completely | Stop processing when a condition is met |