Search code examples
javalabeled-statements

Can java labels be used appropriately outside of for loops?


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!


Solution

  • 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 breaks and continues. 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.