Java Continue Statement

Naveen AnamaneniUpdated · 4 min read

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

continue skips to the next round; break leaves the loop
DailyTotal.java▶ Try it
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);
    }
}
Output
Added Rs. 250
Added Rs. 480
Added Rs. 120
Day total: Rs. 850

How it works

  1. A 0 means a canceled order.
  2. When amount is 0, line 7's continue skips lines 9 and 10 for that round, and the loop moves to the next order.
  3. 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

LoopAfter continue, Java goes to
forThe update (i++), then the condition
for-eachThe next element
whileThe condition
do-whileThe condition at the bottom
OddOnly.java▶ Try it
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();
    }
}
Output
1 3 5 7 9

Here 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 continueWith if
if (amount == 0) { continue; } then the workif (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

  1. Easy: Print the numbers from 1 to 20, skipping multiples of 3.
  2. Harder: Given an array of marks, print the average of only the marks that are 35 or above, using continue to skip the others.

Quick check: continue

4 questions
1What does continue do?
2In a for loop, where does execution go after continue?
3Why can continue cause an infinite while loop?
4What is the day total in DailyTotal if continue is replaced by break?

Key Takeaways

Was this tutorial helpful?

Lesson 64 of 482