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

后端 未结 12 1159
生来不讨喜
生来不讨喜 2020-11-22 08:02

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

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

(line 137 here)

I have never seen this b

相关标签:
12条回答
  • 2020-11-22 08:15

    The question is answered, but as a side note:

    I have heard of interview questions a la "Why is this Java code valid?" (stripped the simpler example; here's the meaner one, thx Tim Büthe):

    url: http://www.myserver.com/myfile.mp3
    downLoad(url);
    

    Would you all know what this code is (apart from awful)?

    Solution: two labels, url and http, a comment www.myserver.com/myfile.mp3 and a method call with a parameter that has the same name (url) as the label. Yup, this compiles (if you define the method call and the local variable elsewhere).

    0 讨论(0)
  • 2020-11-22 08:24

    That's not a keyword, it's a label. It's meant to be used with the break and continue keywords inside nested loops:

    outer:
    for(;;){
        inner:
        for(;;){
            if(){
                break inner; // ends inner loop
            } else {
                break outer; // ends outer loop
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:26

    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.

    0 讨论(0)
  • 2020-11-22 08:27

    It is not a keyword, but a label. If inside the for loop you write break loop;, and you exit that loop.

    0 讨论(0)
  • 2020-11-22 08:30

    It is a label, and labels in Java can be used with the break and continue key words for additional control over loops.

    Here it is explained in a rather good way:

    Thinking in Java, break and continue

    0 讨论(0)
  • 2020-11-22 08:31

    You could write almost anything, as it is a label... You have an example here

    0 讨论(0)
提交回复
热议问题