Java Continue Statement
A teacher checking homework skips any student who was absent and moves on to the next name; they don't stop checking the whole class. continue does that inside a loop: it skips the rest of the current round and goes straight to the next one. The loop itself keeps going.
Skip and Move On
public class DailyTotal {
public static void main(String[] args) {
int[] orders = {250, 0, 480, 0, 120};
int total = 0;
for (int amount : orders) {
if (amount == 0) {
continue;
}
total += amount;
System.out.println("Added Rs. " + amount);
}
System.out.println("Day total: Rs. " + total);
}
}Added Rs. 250
Added Rs. 480
Added Rs. 120
Day total: Rs. 850How it works
- A
0means a canceled order. - When
amountis 0, line 7'scontinueskips lines 9 and 10 for that round, and the loop moves to the next order. - The loop still visits all five orders; only the canceled ones are skipped.
Try it yourself: change continue to break. What's the day total now, and why?
Where continue Jumps To
| Loop | After continue, Java goes to |
|---|---|
for | The update (i++), then the condition |
| for-each | The next element |
while | The condition |
do-while | The condition at the bottom |
public class OddOnly {
public static void main(String[] args) {
int n = 0;
while (n < 9) {
n++;
if (n % 2 == 0) {
continue;
}
System.out.print(n + " ");
}
System.out.println();
}
}1 3 5 7 9Here the update n++ is at the top of the body, before the continue, so it always runs.
continue or if-else?
Both of these do the same thing:
With continue | With if |
|---|---|
if (amount == 0) { continue; } then the work | if (amount != 0) { the work } |
continue reads well when there are several reasons to skip an item at the top of a long body ("skip canceled, skip refunded, skip test orders"), because the main work stays unindented. For one simple case, an if is often just as clear.
Common Mistakes
Skipping the update in a while loop. See the warning above.
Using continue where break was meant. continue never ends the loop.
Using continue outside a loop. It doesn't compile: continue outside of loop.
Practice
- Easy: Print the numbers from 1 to 20, skipping multiples of 3.
- Harder: Given an array of marks, print the average of only the marks that are 35 or above, using
continueto skip the others.
Key Takeaways
Was this tutorial helpful?