So I've seen a lot of cases where labels are being used in for loops to break out, especially with doubly nested loops.
Is this the only case where they can be used? or are there other common uses that I just don't know about. I feel like its a java tool I've never used!
It is fair to say that labeling a loop is the only useful way that a labeled statement can be used.
You are allowed to label any statement in Java, but the only way they are used is as a target of a (labeled) break
or continue
statement.
The usual advice applies though: just because you can do something does not mean you should. Don't use labels as funny "comments" (yes I have seen this done). Don't write doubly nested loops just to show off your ability to break or continue an outer loop. These days we tend to favor operations that apply to a whole sequence, mitigating some uses for labeled break
s and continue
s. As always, aim for readability and simplicity. That said, tools like parser generators that output Java source are quite likely to make heavy use of labeled statements, even if human programmers rarely do.
Labelled break and continue are essentially goto statements.
From https://stackoverflow.com/a/6373262/895245: forward goto:
label: {
// do stuff
if (check) break label;
// do more stuff
}
Backward goto
label: do {
// do stuff
if (check) continue label;
// do more stuff
break label;
} while(true);
So this question comes down to the never ending debate of when goto statements are legitimate, e.g.: Examples of good gotos in C or C++ , with the added fact that the backwards goto idiom above is even uglier than a direct GOTO.
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