I always thought that the labels must be used only with loops but it seems not. Giving such code:
public class LabelTest {
public static void main(String[] args) {
label1: System.out.println("");
label2: LabelTest t = new LabelTest();
}
}
When compiled line labeled "label1" compiles but the code at "label2" gives errors. Why's that? And why would I want to label statements which are not "loops"?
You get an error because a label cannot be applied to variable declarations, that's just how the language grammar is defined (a label can only precede a Statement
, and a LocalVariableDeclarationStatement
is not a Statement
). The reason is probably that it could cause confusion concerning variable scope. This works:
label1: System.out.println("");
label2: { LabelTest t = new LabelTest(); }
To add to Michael Borgwardt's answer, you can do things like this for convenience (I just discovered this the other day while reading through the Java rt.jar source code):
BlockSegment:
if (conditionIsTrue) {
doSomeProcessing ();
if (resultOfProcessingIsFalse()) break BlockSegment;
otherwiseDoSomeMoreProcessing();
// These lines get skipped if the break statement
// above gets executed
}
// This is where you resume execution after the break
anotherStatement();
Now, this is logically equivalent to:
if (conditionIsTrue) {
doSomeProcessing ();
if (!resultOfProcessingIsFalse()) {
otherwiseDoSomeMoreProcessing();
// More code here that gets executed
}
}
anotherStatement();
But, you get to skip some of the extra braces (and indentations that come with braces). Perhaps it looks cleaner (it does in my opinion), and there are some places where this style of coding may be appropriate and less confusing.
So, you may use labels beyond just loops, and even beyond if
statements. For example, this is valid Java syntax (and maybe you could conjure up a reason to do something like this):
statementOne();
statementTwo();
BlockLabel: {
statementThree();
boolean result = statementFour();
if (!result) break BlockLabel;
statementFive();
statementSix();
}
statementSeven();
If the break
gets executed here, then execution skips to the end of the block denoted by the label, and statementFive()
and statementSix()
get skipped.
The usefulness of this style (without an if
statement) becomes more evident when you have blocks within blocks where you must skip around. In general, you can accomplish everything with smart enough use of loops. However, there are a few cases where labels without loops make for easier reading of code. For example, if you need to sequentially check parameters, you may either do this or throw an exception. It ends up being a matter of cleanliness of code and personal style.
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