我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
我对此感到困惑。我们大多数人都听说过Java中没有goto语句。
但我发现它是Java中的关键字之一。它可以在哪里使用?如果它不能使用,那么为什么它作为关键字包含在Java中?
当前回答
James Gosling创建了支持goto语句的原始JVM,但后来他删除了这个不必要的特性。没有必要使用goto的主要原因是,通常可以用可读性更好的语句(如break/continue)或将一段代码提取到方法中来代替它。
来源:James Gosling,问答环节
其他回答
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
关键字const和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在Java中没有使用,尽管它是一个保留字。对于const也是如此。这两个都在c++中使用,这可能是它们被保留的原因;这样做的目的可能是为了避免让迁移到Java的c++程序员感到困惑,也可能是为了在以后的Java版本中保留使用它们的选项。
我也不喜欢goto,因为它通常会降低代码的可读性。然而,我相信这条规则也有例外(特别是涉及词法分析器和解析器时!)
当然,你也可以把程序转换成类似于汇编程序的形式,然后编写类似于
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的代码可读性强多了,不是吗?
因为它不受支持,为什么你想要一个什么都不做的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");
}
}