在其中一个论坛中,我发现下面的代码是一个问题:
public class Test{
public static void main(String[] args){
System.out.println("Hello");
Test:
System.out.println("World");
}
}
Run Code Online (Sandbox Code Playgroud)
并询问结果会是什么?
我认为这将是一个编译时错误,因为我还没有看到Test:java中的代码.我错了,令人惊讶的是,在编译和运行代码之后打印了两行.
任何人都可以告诉我这种Test:代码的用途是什么?为什么不抛错误?
该Test:文本是一个标签,在语言规范中进行了描述,用于break或continue来自内部循环,如以下示例所示:
与C和C++不同,Java编程语言没有goto语句; 标识符语句标签与出现在标记语句中任何位置的break或continue语句(第14.15节,第14.16节)一起使用.
public static void main(String[] args) {
outerLoop:
while (true) {
int i = 0;
while (true) {
System.out.println(i++);
if (i > 5) {
break outerLoop;
}
if (i > 10) {
break;
}
}
System.out.println("Broken inner loop");
}
System.out.println("Broken outer loop");
}
Run Code Online (Sandbox Code Playgroud)