Java中有goto语句吗?

发布于 2024-08-26 22:31:32 字数 108 浏览 5 评论 0原文

我对此很困惑。我们大多数人都被告知 Java 中没有任何 goto 语句。

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

I'm confused about this. Most of us have been told that there isn't any goto statement in Java.

But I found that it is one of the keywords in Java. Where can it be used? If it can not be used, then why was it included in Java as a keyword?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

戏舞 2024-09-02 22:31:32

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

资料来源:詹姆斯·高斯林,问答环节

James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

Source: James Gosling, Q&A session

熊抱啵儿 2024-09-02 22:31:32

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

它位于原始 JVM 中(请参阅 @VitaliiFedorenko 的回答),但后来被删除。它可能被保留为保留关键字,以防将其添加到更高版本的 Java 中。

如果 goto 不在列表中,并且稍后将其添加到语言中,则使用单词 goto 作为标识符(变量名称、方法名称等)的现有代码...)会打破。但是因为 goto 是一个关键字,所以这样的代码现在甚至不会编译,并且仍然可以让它在以后实际执行某些操作,而不会破坏现有代码。

The Java keyword list specifies the goto keyword, but it is marked as "not used".

It was in the original JVM (see answer by @VitaliiFedorenko), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java.

If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

谁与争疯 2024-09-02 22:31:32

该关键字存在,但未实现。

我能想到的使用 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;
    }
}

The keyword exists, but it is not implemented.

The only good reason to use goto that I can think of is this:

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:

In Java you can do this like this:

loops:
for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        break loops;
    }
}
软糯酥胸 2024-09-02 22:31:32

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

“关键字 const 和 goto 是
保留,即使它们不是
目前使用。 ”

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

"The keywords const and goto are
reserved, even though they are not
currently used. "

哀由 2024-09-02 22:31:32

因此,如果语言设计者觉得有需要,有一天它们就可以被使用。

另外,如果具有这些关键字的语言(例如 C、C++)的程序员错误地使用了它们,那么 Java 编译器可以给出有用的错误消息。

或者也许只是为了阻止程序员使用 goto :)

So they could be used one day if the language designers felt the need.

Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.

Or maybe it was just to stop programmers using goto :)

想你只要分分秒秒 2024-09-02 22:31:32

它们保留供将来使用(请参阅:Java 语言关键字)

关键字 const 和 goto 被保留,即使它们当前未被使用。

Java中没有goto语句的原因可以在“Java 语言环境":

Java 没有 goto 语句。研究表明 goto 被(误用)得更频繁,而不仅仅是“因为它在那里”。消除 goto 导致了语言的简化——例如,没有关于 goto 进入 for 语句中间的效果的规则。对大约 100,000 行 C 代码的研究表明,大约 90% 的 goto 语句纯粹是为了获得跳出嵌套循环的效果。如上所述,多级中断和继续消除了大部分 goto 语句的需要。

They are reserved for future use (see: Java Language Keywords)

The keywords const and goto are reserved, even though they are not currently used.

The reason why there is no goto statement in Java can be found in "The Java Language Environment":

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.

妳是的陽光 2024-09-02 22:31:32

如何在 Java 中使用“继续”标签的示例是:

public class Label {
    public static void main(String[] args) {
        int temp = 0;
        out: // label
        for (int i = 0; i < 3; ++i) {
            System.out.println("I am here");
            for (int j = 0; j < 20; ++j) {
                if(temp==0) {
                    System.out.println("j: " + j);
                    if (j == 1) {
                        temp = j;
                        continue out; // goto label "out"
                    }
                }
            }
        }
        System.out.println("temp = " + temp);
    }
}

结果:

I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1

An example of how to use "continue" labels in Java is:

public class Label {
    public static void main(String[] args) {
        int temp = 0;
        out: // label
        for (int i = 0; i < 3; ++i) {
            System.out.println("I am here");
            for (int j = 0; j < 20; ++j) {
                if(temp==0) {
                    System.out.println("j: " + j);
                    if (j == 1) {
                        temp = j;
                        continue out; // goto label "out"
                    }
                }
            }
        }
        System.out.println("temp = " + temp);
    }
}

Results:

I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1
远山浅 2024-09-02 22:31:32

重要的是要理解,goto 结构是程序员使用机器代码和汇编语言编程时代的残余。因为这些语言非常基础(例如,每条指令只做一件事),程序控制流完全通过goto语句完成(但在汇编语言中,这些被称为作为跳转分支指令)。

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

很明显,Java 是 C/C++ 的演变。 Java 与 C 共享许多功能,但抽象了更多细节,因此只是编写方式不同。 Java 是一种非常高级的语言,因此当使用函数、for、foreach 和 while 循环等更高级的结构来执行程序时,根本没有必要使用 goto 等低级功能控制流量。想象一下,如果您在一个函数中,并对另一个函数中的标签执行了 goto 操作。当另一个函数返回时会发生什么?这种想法是荒谬的。

这并不一定能回答为什么 Java 包含 goto 语句但又不让它编译,但重要的是要知道为什么 goto 被首先使用,在较低级别的应用程序,以及为什么在 Java 中使用它没有意义。

It is important to understand that the goto construct is remnant from the days that programmers programmed in machine code and assembly language. Because those languages are so basic (as in, each instruction does only one thing), program control flow is done completely with goto statements (but in assembly language, these are referred to as jump or branch instructions).

Now, although the C language is fairly low-level, it can be thought of as very high-level assembly language - each statement and function in C can easily be broken down into assembly language instructions. Although C is not the prime language to program computers with nowadays, it is still heavily used in low level applications, such as embedded systems. Because C's function so closely mirrors assembly language's function, it only makes sense that goto is included in C.

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.

This does not necessarily answer why Java includes the goto statement yet won't let it compile, but it is important to know why goto was ever used in the first place, in lower-level applications, and why it just doesn't make sense to be used in Java.

晨光如昨 2024-09-02 22:31:32

因为它不受支持,为什么您需要一个不执行任何操作的 goto 关键字或一个名为 goto 的变量?

尽管您可以使用 break label;continue label; 语句来有效地执行 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");
     }
}

Because it's not supported and why would you want a goto keyword that did nothing or a variable named goto?

Although you can use break label; and continue label; statements to effectively do what goto does. But I wouldn't recommend it.

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");
     }
}
万劫不复 2024-09-02 22:31:32

不,不使用 goto,但您可以定义标签并在标签上留下一个循环。您可以使用 breakcontinue 后跟标签。这样你就可以跳出不止一层循环。请查看教程

No, goto is not used, but you can define labels and leave a loop up to the label. You can use break or continue followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.

他夏了夏天 2024-09-02 22:31:32

不,幸运的是,Java 中没有 goto

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

No, thankfully, there isn't goto in Java.

The goto keyword is only reserved, but not used (the same goes for const).

老娘不死你永远是小三 2024-09-02 22:31:32

不,goto 在 Java 中并未使用,尽管它是一个保留字。 const 也是如此。这两个都在 C++ 中使用,这可能就是它们被保留的原因;其目的可能是为了避免迁移到 Java 的 C++ 程序员感到困惑,也可能是为了保留在 Java 的后续版本中使用它们的选择。

No, goto is not used in Java, despite being a reserved word. The same is true for const. Both of these are used in C++, which is probably the reason why they're reserved; the intention was probably to avoid confusing C++ programmers migrating to Java, and perhaps also to keep the option of using them in later revisions of Java.

雾里花 2024-09-02 22:31:32

是的,这是可能的,但不如 C# 中的那么好(在我看来,C# 更好!)。 goto 总是掩盖软件的观点是愚蠢的!遗憾的是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");
 }

Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.

Jump to forward:

 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");
 }

Jump to backward:

 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");
 }
新人笑 2024-09-02 22:31:32

我也不喜欢 goto,因为它通常会降低代码的可读性。然而我确实相信这个规则有例外(特别是当涉及到词法分析器和解析器时!)

当然,你总是可以通过将你的程序翻译成类似汇编程序的东西来将你的程序变成 Kleene 范式,然后编写类似的东西

int line = 1;
boolean running = true;
while(running)
{
    switch(line++)
    {
        case 1: /* line 1 */
                break;
        case 2: /* line 2 */
                break;
        ...
        case 42: line = 1337; // goto 1337
                break;
        ...
        default: running = false;
                break;
    }
}

(所以你基本上编写一个执行二进制代码的虚拟机...其中 line 对应于指令指针)

这比使用 goto 的代码更具可读性,不是吗?

I'm not a fan of goto either, as it usually makes code less readable. However I do believe that there are exceptions to that rule (especially when it comes to lexers and parsers!)

Of Course you can always bring your program into Kleene Normalform by translating it to something assembler-like and then write something like

int line = 1;
boolean running = true;
while(running)
{
    switch(line++)
    {
        case 1: /* line 1 */
                break;
        case 2: /* line 2 */
                break;
        ...
        case 42: line = 1337; // goto 1337
                break;
        ...
        default: running = false;
                break;
    }
}

(So you basically write a VM that executes your binary code... where line corresponds to the instruction pointer)

That is so much more readable than code that uses goto, isn't it?

绝不放开 2024-09-02 22:31:32

替换 goto 的大多数良性用法

  • 请注意,您可以通过

    return

  • break

  • breaklabel

  • 扔进try-catch-finally

Note that you can replace most of the benign uses of goto by

  • return

  • break

  • break label

  • throw inside try-catch-finally

两相知 2024-09-02 22:31:32

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

虽然 Java 没有 goto,但它有一些与 goto 的某些用法相对应的结构,即能够 breakcontinue< /code> 带有命名循环。另外,finally 可以被认为是一种扭曲的 goto

As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.

Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.

如此安好 2024-09-02 22:31:32

禁止声明同名变量。

例如
int i = 0,转到;

To prohibit declarations of variables with the same name.

e.g.
int i = 0, goto;

寄风 2024-09-02 22:31:32

它在很大程度上被认为是您不应该做的事情之一,但可能被列为保留字以避免开发人员感到困惑。

It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.

三五鸿雁 2024-09-02 22:31:32

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

如果您被告知 Java 中没有 goto 语句,那么您就被愚弄了。事实上,Java 由两层“源”代码组成。

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

If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.

彻夜缠绵 2024-09-02 22:31:32

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

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

goto是保留的,即使它当前没有使用,但永远不要说永远:)

See the following link is shows all java reserved words and tells you what versions they where added.

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

goto is reserved, even though it is not currently used, never say never however :)

筱果果 2024-09-02 22:31:32

当然它是关键字,但它不是在源代码级别使用的。

但是如果你使用 jasmin 或其他较低级别的语言,将其转换为字节码,那么“goto”就在那里

Of course it is keyword, but it is not used on level of source code.

But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there

野鹿林 2024-09-02 22:31:32

因为虽然Java语言不使用它,但是JVM字节码却使用它。

Because although the Java language doesn't use it, JVM bytecode does.

枫林﹌晚霞¤ 2024-09-02 22:31:32

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; 
            }   
   }

goto is not in Java

you have to use GOTO
But it don't work correctly.in key java word it is not used.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

   public static void main(String[] args) {            
            GOTO me;
            //code;
            me:
            //code; 
            }   
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文