Search code examples
javalabeled-statements

"loop:" in Java code. What is this, and why does it compile?


This code just made me stare at my screen for a few minutes:

loop:
for (;;) {
    // ...
}

(line 137 here)

I have never seen this before, and I had no idea Java has a "loop" keyword (NetBeans doesn't even color it like a keyword), and it does compile fine with JDK 6.

What is the explanation?


Solution

  • It is not a keyword it is a label.

    Usage:

        label1:
        for (; ; ) {
            label2:
            for (; ; ) {
                if (condition1) {
                    // break outer loop
                    break label1;
                }
                if (condition2) {
                    // break inner loop
                    break label2;
                }
                if (condition3) {
                    // break inner loop
                    break;
                }
            }
        }
    

    Documentation.