Is using a labeled break a good practice in Java?

No, it’s not like a goto, since you can’t “go” to another part of the control flow.

From the page you linked:

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

This means you can only break loops that are currently being executed.

Consider this example:

first:
for( int i = 0; i < 10; i++) {
  second:
  for(int j = 0; j < 5; j ++ )
  {
    break xxx;
  }
}

third:
for( int a = 0; a < 10; a++) {

}

You could replace xxx with first or second (to break the outer or inner loop), since both loops are being executed, when you hit the break statement, but replacing xxx with third won’t compile.

Leave a Comment