break, continue & Labeled Loops in Java
break exits a loop (or a switch) immediately, skipping any remaining iterations entirely; continue skips just the rest of the current iteration's body and jumps straight to the next one, without leaving the loop altogether. Both work automatically on the innermost loop they're written inside β which is exactly where labeled loops come in: prefixing a loop with a label, like outer:, and then writing break outer; or continue outer; from inside a nested loop lets that statement target the labeled outer loop specifically, instead of only the nearest one.
Labeled break and continue exist specifically for nested loops, since an unlabeled break or continue inside a nested loop can only ever affect the loop it's directly inside. Reaching an outer loop from deep inside a nested one otherwise usually requires an extra boolean flag checked at each level, which labels avoid entirely.
break
Exits the loop it's directly inside immediately, skipping every remaining iteration.
continue
Skips the rest of the current iteration's body only, then moves on to the next iteration as normal.
Both default to the innermost loop
An unlabeled break or continue only ever affects the loop it's written directly inside, never an outer one.
Labeling a loop
Writing a name followed by a colon, like outer:, right before a loop lets that specific loop be targeted from anywhere inside it.
Labeled break and continue
break outer; or continue outer; from inside a nested loop acts on the labeled outer loop specifically, not the nearest enclosing one.
public class BreakContinueDemo { public static void main(String[] args) { outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) { continue outer; } System.out.println(i + "," + j); } } }}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself β building beats watching.