break and continue
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)break stops a loop at once, and continue skips the rest of the current round and moves on to the next one. Both usually sit inside an if, so they act only in the rounds you choose.
break: stop the loop now
You want the first number after 50 that 7 divides exactly; once 56 is found, checking the rest is wasted work. break ends the loop at once and jumps to the first line after it, even if the condition is still true.
Example 1 · First multiple of 7 after 50
public class FirstSeven { public static void main(String[] args) { for (int n = 51; n <= 100; n++) { if (n % 7 == 0) { System.out.println("Found: " + n); break; } } System.out.println("Search over"); }}Found: 56 Search over
What this code does
- The loop could run up to 100, but
breakstops it in the round wherenis 56. - Only 6 rounds run (51 to 56) instead of 50.
You may know break already from switch (opens in a new tab), where it ends a case in the same way.
continue: skip just this round
Roll number 4 has left the school, so the attendance loop should skip 4 and carry on with 5 and 6. continue skips the rest of the body for this round only.
Example 2 · Skip an absent roll number
public class Attendance { public static void main(String[] args) { for (int roll = 1; roll <= 6; roll++) { if (roll == 4) { continue; } System.out.println("Roll " + roll + ": present"); } }}Roll 1: present Roll 2: present Roll 3: present Roll 5: present Roll 6: present
What this code does
- When
rollis 4,continueskips the print for that round only. - The update
roll++still runs, so the loop goes on with 5 and 6.
break and continue side by side
Both jump out of the normal flow, so they are easy to mix up. Remember it this way: continue leaves the round, break leaves the loop.
The picture shows both on the same six rounds. Then step through a loop that uses both and watch which lines are skipped.
Trace the code
continue at 3, break at 5
Variables
- i
- 1
Output
(nothing printed yet)Line 3Start: i = 1. Is 1 <= 6? Yes.
The continue trap in a while loop
In a while loop, the update is just an ordinary line in the body. If continue jumps over it, the counter never changes and the loop never ends.
int i = 0;while (i < 6) { if (i == 3) { continue; // jumps back to the check: i stays 3 forever } System.out.println(i); i++; // never reached once i is 3}Put the update before the continue, at the top of the body, or use a for loop, where the update runs even after a continue.
Example 3 · Skip 3 safely in a while loop
public class SafeSkip { public static void main(String[] args) { int i = 0; while (i < 6) { i++; if (i == 3) { continue; } System.out.println(i); } }}1 2 4 5 6
What this code does
- The update
i++is the first line of the body, socontinuecan never jump over it. - Because
igrows before it is printed, the loop prints 1 to 6 instead of 0 to 5.
Next step
Check your understanding
8 quick questions