我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
它们被保留以供将来使用(请参阅:Java语言关键字)
关键字const和goto是保留的,即使它们目前没有被使用。
Java中没有goto语句的原因可以在“Java语言环境”中找到:
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
其他回答
因为尽管Java语言不使用它,但JVM字节码使用它。
不,谢天谢地,Java中没有goto。
goto关键字只保留,但不使用(const也是如此)。
请注意,您可以将goto的大多数良性用途替换为by
返回 打破 打破标签 扔进去,试着抓住,最后
是的,这是可能的,但不像在c#(在我看来,c#更好!)那些总是模糊软件的观点是愚蠢的!很遗憾java没有至少goto case xxx。
跳转向前:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
向后跳:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
Java关键字列表指定了goto关键字,但它被标记为“未使用”。
它在最初的JVM中(参见@VitaliiFedorenko的回答),但后来被删除了。它可能被保留为一个保留关键字,以防它被添加到Java的后期版本中。
如果goto不在列表中,并且它后来被添加到语言中,使用单词goto作为标识符(变量名、方法名等)的现有代码将被破坏。但是因为goto是一个关键字,这样的代码在当前甚至不会编译,并且它仍然有可能在不破坏现有代码的情况下让它实际做一些事情。