Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The break statement

The break statement: An unlabeled break statement exits the nearest loop or switch statement, while a labeled break transfers control beyond its labeled block or loop.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

break

An unlabeled break statement exits the nearest loop or switch statement, while a labeled break transfers control beyond its labeled block or loop.

Use break for a clear early end to a search; use a label sparingly when leaving several nested loops.

break exits only the nearest matching construct, not the method; a switch expression returns a value with yield, not the former value-bearing break syntax.

A finally block runs while control leaves through break, the label must enclose its target statement, and break outside a loop, switch, or labeled block is a compile-time error.

The labeled break stops both loops at break@1,1, and visits=5 proves that later iterations did not run.

Examples

public class Main {
  public static void main(String[] args){ int visits=0; outer: for(int row=0;row<3;row++){ for(int col=0;col<3;col++){ visits++; if(row==1&&col==1){System.out.println("break@"+row+","+col);break outer;} } } System.out.println("visits="+visits); }
}

Result

break@1,1
visits=5

The labeled break stops both loops at break@1,1, and visits=5 proves that later iterations did not run.

Sources