Java标签用法

Jay*_*esh 5 java

在某个地方浏览java好文章,我发现这样的代码完美编译.

public int myMethod(){
    http://www.google.com
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

描述说http:该词将被视为标签和//www.google.com评论

我不知道Java Label在循环外是如何有用的?在什么情况下应该使用Java Label外部循环?

Eng*_*uad 11

以下是在Java中使用标签的一个好处:

block:
{
    // some code

    if(condition) break block;

    // rest of code that won't be executed if condition is true
}
Run Code Online (Sandbox Code Playgroud)

嵌套循环的另一种用法:

outterLoop: for(int i = 0; i < 10; i++)
{
    while(condition)
    {
        // some code

        if(someConditon) break outterLoop; // break the for-loop
        if(anotherConditon) break; // break the while-loop

        // another code
    }

    // more code
}
Run Code Online (Sandbox Code Playgroud)

要么:

outterLoop: for(int i = 0; i < 10; i++)
{
    while(condition)
    {
        // some code

        if(someConditon) continue outterLoop; // go to the next iteration of the for-loop
        if(anotherConditon) continue; // go to the next iteration of the while-loop

        // another code
    }

    // more code
}
Run Code Online (Sandbox Code Playgroud)