Skip to content
Tutorials Center
My learning

Topics

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.

Java
break;
break label;
continue;
continue label;

Try it

Java break and continue in a loop

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.

Java Labeled break and continue

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

  • break in a switch ends the switch only, not an enclosing loop. To leave a loop from inside a switch, use a label or return.
  • Arrow-form switches do not fall through, so they do not need break. A break or continue cannot jump out of a switch expression; use yield for the value.
  • continue in a for loop still runs the update part (i++). In a while loop, make sure the variable that ends the loop is changed before continue, 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 return is often clearer.
  • Not allowed in lambdas: a break or continue cannot leave the enclosing loop from inside a lambda body, for example in forEach.
  • A finally block runs before control leaves through break or continue.
  • Dead code: statements directly after break, continue or return in the same block do not compile (unreachable statement).