for(int x = 0; x < 5; x++)
stop2: {
System.out.println("Count");
if (x == 2)
break stop2;
}
stop3: for(int x = 0; x < 5; x++) {
System.out.println("Second");
if (x == 2)
break stop3;
}
While I was learning the labeled break in Java, I noticed that putting the label just before and after the for statement would have different results. In the code above, the for loop with stop2 does not stop after printing "Count" 3 times while the other one does. Can somebody explain the difference between these two? I thought the labeled break breaks the body right after the label...
I thought the labeled break breaks the body right after the label.
No. It breaks the statement (or block) to which the label is attached.
Thus:
for (int x = 0; x < 5; x++)
stop2: {
// stuff
break stop2;
}
breaks the body statement of the for loop, but
stop3: for (int x = 0; x < 5; x++)
{
//stuff
break stop3;
}
breaks the for statement.
Contrast the above this with
for (int x = 0; x < 5; x++)
{
//stuff
break;
}
An ordinary (non-labelled) break can only be used in a loop or a switch statement, and it breaks the immediately enclosing loop or switch.
This is what JLS 14.15 says about this:
"A
breakstatement with no label attempts to transfer control to the innermost enclosingswitch,while,do, orforstatement of the immediately enclosing method or initializer; this statement, which is called the break target, then immediately completes normally.""A
breakstatement with labelIdentifierattempts to transfer control to the enclosing labeled statement (§14.7) that has the sameIdentifieras its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be aswitch,while,do, orforstatement."
Thus, the key thing in determining what a break statement (ordinary or labelled) does is what the break target is.
This is all a bit obscure ... and another good reason to use labelled statements only when they are absolutely necessary. I cannot see the justification for using them in your examples (except as illustrations). One of them should be written as an ordinary break and the other should be written as a continue.
But (for the doubters) both of those examples are valid, compilable Java code and both have well defined meaning according to the JLS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With