Can the label for a break have any name?

4047 views java
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.

answered question

It has to be a valid identifier. a1 is fine. 1a is not.

@ElliottFrisch Thank you!

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.

1 Answer

12

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.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories