“loop:” in Java code. What is this, why does it co

2018-12-31 15:23发布

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.

Can someone explain this to me?

12条回答
梦醉为红颜
2楼-- · 2018-12-31 15:28

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

查看更多
梦寄多情
3楼-- · 2018-12-31 15:32

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

查看更多
春风洒进眼中
4楼-- · 2018-12-31 15:32

It's a label, though look at the following example:

int a = 0;
int b = 0
while (a<10){
    firstLoop:
    a++;
    while(true){
        b++
        if(b>10){
            break firstLoop;
        }
    }
 }

When b>10 the execution flow goes to the outer loop

查看更多
步步皆殇っ
5楼-- · 2018-12-31 15:33

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: http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ305_024.htm

查看更多
骚的不知所云
6楼-- · 2018-12-31 15:36

it is a label. generaly label used in java to transfer the control flow at desired location while all keyword like continue, break have a specified chice of location.

查看更多
美炸的是我
7楼-- · 2018-12-31 15:37

Its a break point label, to allow you to break out of a specified loop, rather than simply the innermost one you happen to be in.

Its used on line 148

查看更多
登录 后发表回答