2

Shouldn't this loop infinitely?

someLabel:{
        for (int i = 0; i < 5; ++i) {
            System.out.println(i);
            if (i == 3)
                break someLabel;
        }
}

It goes

0
1
2
3

Then dies. I was reading a question about an alternative to GOTO in Java. This was the accepted answer: https://stackoverflow.com/a/2430789/555690. Shouldn't the for loop be executed again?

Community
  • 1
  • 1
Saturn
  • 17,888
  • 49
  • 145
  • 271

2 Answers2

1

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

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.

Apart from the fact that I never saw any real code using this kind of control flow, I guess a use for it would be to break an outer loop from an inner loop (as described in the provided link):

search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length;
             j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search;
            }
        }
    }
Mathieu Fortin
  • 1,048
  • 7
  • 17
0

The Java language specification states

A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (ยง14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally.

The statement here is actually a block statement. Once you break, that block ends.

So, no, the for loop should not iterate again since it's inside the block that just ended.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724