1

I am learning java after coming over from python. The book I am reading is currently discussing breaks, which I am familiar with. When it comes to labeled breaks, can I give the label any name I choose (barring keywords)? Another thing, how do I end the scope of the label?

Note: The book didn't really specify. I am assuming yes but if there are any rules and guidelines that are different from standard naming conventions please let me know.

Caleb Suhy
  • 61
  • 7
  • It has to be a valid identifier. `a1` is fine. `1a` is not. – Elliott Frisch Nov 08 '18 at 23:53
  • @ElliottFrisch Thank you! – Caleb Suhy Nov 08 '18 at 23:54
  • 3
    Note that, in 20 years of reading and writing Java code, I can't remember having found a single label in actual Java code. They're not considered as good practice, and nobody uses them. – JB Nizet Nov 08 '18 at 23:56
  • @JBNizet Thanks for the info. I'm learning to program as a 14 yo. Any recommended open source projects I should look at to improve both my style and habits? – Caleb Suhy Nov 09 '18 at 00:10
  • 1
    @JBNizet I can't remember where, but I'm pretty sure I've seen labels in core Java/JavaFX libraries. Not often, mind you, but not zero either. That's not to say I think they're a good choice; I agree they should be avoided as much as possible. – Slaw Nov 09 '18 at 00:44

1 Answers1

2

You can label your loops and then use labeled breaks:

outer: for(int i = 0; i < 10; i++) {
  for(int j = 0; j < 10; j++) {
    System.out.println(i + "," + j);
    break outer;
  }
}

Output will be 0,0, since it breaks the outer loop on the first iteration of the inner loop.

Badashi
  • 1,124
  • 9
  • 18