goto in Java bytecode

2019-01-24 00:33发布

So the other day when I was looking at the wikipedia page for Java bytecode I came across this example:

Consider the following Java code:

  outer:
  for (int i = 2; i < 1000; i++) {
      for (int j = 2; j < i; j++) {
          if (i % j == 0)
          continue outer;
     }
     System.out.println (i);
  }

A Java compiler might translate the Java code above into byte code as follows, assuming the above was put in a method:

  0:   iconst_2
  1:   istore_1
  2:   iload_1
  3:   sipush  1000
  6:   if_icmpge       44
  9:   iconst_2
  10:  istore_2
  11:  iload_2
  12:  iload_1
  13:  if_icmpge       31
  16:  iload_1
  17:  iload_2
  18:  irem
  19:  ifne    25
  22:  goto    38
  25:  iinc    2, 1
  28:  goto    11
  31:  getstatic       #84; //Field java/lang/System.out:Ljava/io/PrintStream;
  34:  iload_1
  35:  invokevirtual   #85; //Method java/io/PrintStream.println:(I)V
  38:  iinc    1, 1
  41:  goto    2
  44:  return

And I notice that little word goto appears a couple of times, which upon checking the JVM specification is valid. My question is why? GOTO is a reserved but unusable keyword in Java, so why when we write and compile java code does it seem to get compiled with goto back into it. I am wondering it this is just the way things have always been done at a lower level of programming, or whether it is because the JVM is trusted to use the goto word more effectively. Ultimately I am curious as to why goto is considered such bad practice that it is prohibited in java code, yet seems to be put straight back into your code when compiled.

标签: java goto
9条回答
对你真心纯属浪费
2楼-- · 2019-01-24 01:27

bytecode isn't Java, programs in other languages, like Groovy, can be compiled into bytecode, you can write bytecode directly using some tools like BCEL. As for goto you cannot go without it at low level.

查看更多
倾城 Initia
3楼-- · 2019-01-24 01:27
  1. SpaceTrucker mentioned (in comments to head question) a difference between the Java language itself and bytecode. The goto keyword and goto instruction are not the same. The only common thing is the name. In case of bytecode it is just an instruction of JUMP (JMP);
  2. Basically, goto is thought to be a bad practice in programming/coding, because of realizing the 'spagetti' code and making worse the readability of code.
查看更多
forever°为你锁心
4楼-- · 2019-01-24 01:32

Java structured programming features such as loops (for/ while) are implemented at the bytecode level with conditional branch (IF..) and unconditional jump (GOTO) instructions.

break or continue to an outer loop are also considered sufficiently useful & legitimate within structured programming, that the Java language has these features (break/ continue to label).

At the JVM/ bytecode level, these are also implemented with GOTO.

See:

查看更多
登录 后发表回答