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

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


当前回答

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

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

其他回答

是的,这是可能的,但不像在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。

goto关键字只保留,但不使用(const也是如此)。

理解goto结构是程序员用机器代码和汇编语言编程时遗留下来的,这一点很重要。因为这些语言非常基础(每条指令只做一件事),程序控制流完全由goto语句完成(但在汇编语言中,这些被称为跳转或分支指令)。

现在,虽然C语言是相当低级的,但它可以被认为是非常高级的汇编语言——C中的每个语句和函数都可以很容易地分解成汇编语言指令。尽管C语言不是当今计算机编程的主要语言,但它仍然在低级应用程序中大量使用,例如嵌入式系统。因为C语言的函数非常接近汇编语言的函数,所以只有在C中包含goto才有意义。

It is clear that Java is an evolution of C/C++. Java shares a lot of features from C, but abstracts a lot more of the details, and therefore is simply written differently. Java is a very high-level language, so it simply is not necessary to have low-level features like goto when more high-level constructs like functions, for, for each, and while loops do the program control flow. Imagine if you were in one function and did a goto to a label into another function. What would happen when the other function returned? This idea is absurd.

这并不一定能回答为什么Java包含goto语句却不让它编译,但重要的是要知道为什么goto在较低级的应用程序中首先被使用,以及为什么在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保留字,并告诉您添加了哪些版本。

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

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