我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
理解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中使用它没有意义。
其他回答
理解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中使用它没有意义。
因为它不受支持,为什么你想要一个什么都不做的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");
}
}
因为尽管Java语言不使用它,但JVM字节码使用它。
James Gosling创建了支持goto语句的原始JVM,但后来他删除了这个不必要的特性。没有必要使用goto的主要原因是,通常可以用可读性更好的语句(如break/continue)或将一段代码提取到方法中来代替它。
来源:James Gosling,问答环节
如何在Java中使用"continue"标签的例子是:
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