avgvstvs avgvstvs - 5 months ago 17
Java Question

Is using a labeled break a good practice in Java?

I'm staring at some old code from 2001 and came across this statement:

else {
do {
int c = XMLDocumentFragmentScannerImpl.this.scanContent();
if (c == 60) {
XMLDocumentFragmentScannerImpl.this.fEntityScanner.scanChar();
XMLDocumentFragmentScannerImpl.this.setScannerState(1);
break label913:
}


I had never seeen this before, and discovered labeled breaks here:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Doesn't this essentially function like
goto
? Is it even good practice to use it? It makes me uneasy.

Answer

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.