Part 03 / Topic 7 of 8
break and continue
break stops a loop completely — execution jumps to the first line after the loop. Use it to stop early once you have found what you needed, or hit a value that means "stop here."
int[] deposits = {500, 1200, -1, 800, 300};
int total = 0;
for (int deposit : deposits) {
if (deposit == -1) {
System.out.println("Sentinel -1 found, stopping the count.");
break;
}
total += deposit;
System.out.println("Added " + deposit + ", running total " + total);
}
System.out.println("Final total before the sentinel: " + total);
Output:
Added 500, running total 500
Added 1200, running total 1700
Sentinel -1 found, stopping the count.
Final total before the sentinel: 1700
Note that 300, after the -1, is never looked at — break leaves the loop for good, not just that one pass.
continue skips only the rest of the current pass and moves straight to the next one — the loop itself keeps running.
int[] amounts = {500, -200, 0, 1000, -50, 300};
int total = 0;
int skipped = 0;
for (int amount : amounts) {
if (amount <= 0) {
skipped++;
continue; // skip zero and negative amounts, keep scanning
}
total += amount;
System.out.println("Counted " + amount + ", running total " + total);
}
System.out.println("Skipped " + skipped + " invalid amounts. Final total: " + total);
Output:
Counted 500, running total 500
Counted 1000, running total 1500
Counted 300, running total 1800
Skipped 3 invalid amounts. Final total: 1800
The two combine naturally: continue past entries that are merely bad, break the moment you hit something that means "stop entirely."
int[] queue = {200, -10, 400, 0, 999999, 150};
int processed = 0;
for (int amount : queue) {
if (amount == 999999) {
System.out.println("Fraud-test amount hit, stopping the queue.");
break;
}
if (amount <= 0) {
continue; // not fraud, just invalid: skip and keep going
}
processed += amount;
}
System.out.println("Processed before stopping: " + processed);
Output:
Fraud-test amount hit, stopping the queue.
Processed before stopping: 600
150 is never processed either — the break on 999999 happens before the loop ever reaches it.
⚠️ The one mistake almost everyone makes:
breakinside aswitchthat is itself inside a loop only exits the switch — the loop keeps going. If you need a menucaseto end the loop (like "Exit" in Section 8), set abooleanflag instead and check it in the loop's own condition.
Full program: examples/06_break_continue.java.
Done here? The practice set for Part 3 — including the solutions — is on the part page.