• Post Reply Bookmark Topic Watch Topic
  • New Topic

Break with label  RSS feed

 
J Mohandos
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quoting the JLS:

A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a switch, while, do, or for statement.

http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.15

I am creating a program keeping in mind the part in bold above. But I am getting compile time error. The code is here

 
Paweł Baczyński
Bartender
Posts: 2074
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quoting the JLS:

A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label.

The statement labelled by label1 is System.out.println("outer loop") which IS NOT enclosing break label1.

The part saying the break target need not be a switch, while, do, or for statement means that you can, for example, write:This prints:
Before break
After labelled statement


The if statement is there so the compiler does not complain about unreachable statement
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note that break should be used with, as they say these days, an "overabundance of caution." If you can avoid using it, do so. I have used it literally maybe a handful of times in over a decade of programming in Java.
 
Robert D. Smith
Ranch Hand
Posts: 221
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Please note that break should be used with, as they say these days, an "overabundance of caution." If you can avoid using it, do so. I have used it literally maybe a handful of times in over a decade of programming in Java.

^^^This

I go back a little further than a decade -- and I can only recall one time in the past 30 years where I couldn't come up with a work around using break (in Visual Basic). Used to drive my boss nuts because I was writing COBOL without gotos. A little design work before coding can usually eliminate the need for such 'short cuts'.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!