Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 735
Jay Smith Avatar asked May 15 '13 01:05

Jay Smith


2 Answers

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.

like image 116
Ray Toal Avatar answered Sep 21 '22 17:09

Ray Toal


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.