Search code examples
javafor-loopbreaklabeled-statements

Labeled break just after loop not working in Java


for(int x = 0; x < 5; x++)
        stop2: {
                System.out.println("Count");
                if (x == 2)
                    break stop2;
        }

        stop3: for(int x = 0; x < 5; x++) {
                System.out.println("Second");
                if (x == 2)
                    break stop3;
        } 

While I was learning the labeled break in Java, I noticed that putting the label just before and after the for statement would have different results. In the code above, the for loop with stop2 does not stop after printing "Count" 3 times while the other one does. Can somebody explain the difference between these two? I thought the labeled break breaks the body right after the label...


Solution

  • I thought the labeled break breaks the body right after the label.

    No. It breaks the statement (or block) to which the label is attached.

    Thus:

      for (int x = 0; x < 5; x++)
          stop2: {
                // stuff
                break stop2;
          }
    

    breaks the body statement of the for loop, but

     stop3: for (int x = 0; x < 5; x++)
          {
              //stuff
              break stop3;
          }
    

    breaks the for statement.

    Contrast the above this with

    for (int x = 0; x < 5; x++)
          {
              //stuff
              break;
          }
    

    An ordinary (non-labelled) break can only be used in a loop or a switch statement, and it breaks the immediately enclosing loop or switch.

    This is what JLS 14.15 says about this:

    "A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer; this statement, which is called the break target, then immediately completes normally."

    "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."

    Thus, the key thing in determining what a break statement (ordinary or labelled) does is what the break target is.


    This is all a bit obscure ... and another good reason to use labelled statements only when they are absolutely necessary. I cannot see the justification for using them in your examples (except as illustrations). One of them should be written as an ordinary break and the other should be written as a continue.

    But (for the doubters) both of those examples are valid, compilable Java code and both have well defined meaning according to the JLS.