Java Reference ยท Keywords and Statements
The break and continue statements
Reference for Java break and continue: leaving loops and switches, skipping iterations, labeled break and continue for nested loops, and pitfalls.
break ends the innermost enclosing loop or classic switch immediately; execution continues after it. continue abandons the rest of the current loop iteration and moves on to the next one. Both can take a label to act on an outer statement instead of the innermost one.
They are useful for early exits: stop searching once you have found a match, skip invalid items, or leave a nested loop in one step.
break; break label; continue; continue label;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
| Form | Meaning |
|---|---|
break; |
Exit the innermost for, while, do-while or classic switch statement. |
break label; |
Exit the labeled statement. The label may be on a loop, a block or any other statement. |
continue; |
Skip to the next iteration of the innermost loop. |
continue label; |
Skip to the next iteration of the labeled loop. The label must be on a loop. |
Usage notes
breakin aswitchends the switch only, not an enclosing loop. To leave a loop from inside a switch, use a label orreturn.- Arrow-form switches do not fall through, so they do not need
break. Abreakorcontinuecannot jump out of a switch expression; useyieldfor the value. continuein aforloop still runs the update part (i++). In awhileloop, make sure the variable that ends the loop is changed beforecontinue, or you may loop forever.- A label is an identifier followed by a colon placed directly before the statement. Labels are rarely needed; extracting the nested loops into a method and using
returnis often clearer. - Not allowed in lambdas: a
breakorcontinuecannot leave the enclosing loop from inside a lambda body, for example inforEach. - A
finallyblock runs before control leaves throughbreakorcontinue. - Dead code: statements directly after
break,continueorreturnin the same block do not compile (unreachable statement).
Related
for,whileanddo-while, Labeled statements,return- Lessons: break and continue, for loops