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

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


当前回答

goto不在Java中

你必须使用GOTO 但它不能正常工作。在关键的Java词中,它没有被使用。 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

   public static void main(String[] args) {            
            GOTO me;
            //code;
            me:
            //code; 
            }   
   }

其他回答

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto

如果有人告诉你Java中没有goto语句,那你就被骗了。事实上,Java由两层“源代码”组成。

James Gosling创建了支持goto语句的原始JVM,但后来他删除了这个不必要的特性。没有必要使用goto的主要原因是,通常可以用可读性更好的语句(如break/continue)或将一段代码提取到方法中来代替它。

来源:James Gosling,问答环节

正如前面所指出的,Java中没有goto,但是关键字是保留的,以防有一天Sun想要将goto添加到Java中。他们希望能够在不破坏太多代码的情况下添加它,所以他们保留了关键字。注意,在Java 5中,他们添加了enum关键字,也没有破坏那么多代码。

虽然Java没有goto,但它有一些结构对应于goto的一些用法,即能够中断和继续命名循环。最后也可以被认为是一种扭曲的后向。

不,没有使用goto,但是您可以定义标签并留下一个到标签的循环。您可以使用break或continue后跟标签。所以你可以跳出多个循环层。看看教程。

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