Caleb Suhy
Caleb Suhy

Reputation: 61

Can the label for a break have any name?

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.

Upvotes: 1

Views: 56

Answers (1)

Badashi
Badashi

Reputation: 1170

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.

Upvotes: 2

Related Questions