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

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


当前回答

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

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

其他回答

不,goto在Java中没有使用,尽管它是一个保留字。对于const也是如此。这两个都在c++中使用,这可能是它们被保留的原因;这样做的目的可能是为了避免让迁移到Java的c++程序员感到困惑,也可能是为了在以后的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中使用"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

关键字存在,但没有实现。

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

禁止声明同名变量。

如。 Int I = 0, goto;