我对此感到困惑。我们大多数人都听说过Java中没有goto语句。

但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?


当前回答

关键字存在,但没有实现。

我能想到的使用goto的唯一好理由是:

for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        goto outsideloops; // to break out of both loops
    }
}
outsideloops:

在Java中,你可以这样做:

loops:
for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        break loops;
    }
}

其他回答

它被认为是不能做的事情之一,但可能被列为保留词,以避免开发人员感到困惑。

请参阅下面的链接,它显示了所有java保留字,并告诉您添加了哪些版本。

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

Goto是保留的,即使目前没有使用,但永远不要说永远:)

Java关键字列表指定了goto关键字,但它被标记为“未使用”。

它在最初的JVM中(参见@VitaliiFedorenko的回答),但后来被删除了。它可能被保留为一个保留关键字,以防它被添加到Java的后期版本中。

如果goto不在列表中,并且它后来被添加到语言中,使用单词goto作为标识符(变量名、方法名等)的现有代码将被破坏。但是因为goto是一个关键字,这样的代码在当前甚至不会编译,并且它仍然有可能在不破坏现有代码的情况下让它实际做一些事情。

它们被保留以供将来使用(请参阅: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.

因为它不受支持,为什么你想要一个什么都不做的goto关键字或者一个名为goto的变量?

虽然你可以使用break标签;并继续标签;语句来有效地做goto所做的事情。但我不建议这么做。

public static void main(String [] args) {

     boolean t = true;

     first: {
        second: {
           third: {
               System.out.println("Before the break");

               if (t) {
                  break second;
               }

               System.out.println("Not executed");
           }

           System.out.println("Not executed - end of second block");
        }

        System.out.println("End of third block");
     }
}