goto in Java bytecode

后端 未结 9 656
一向
一向 2020-12-16 11:58

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:

相关标签:
9条回答
  • 2020-12-16 12:33
    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.
    0 讨论(0)
  • 2020-12-16 12:34

    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:

    • https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
    • http://www.artima.com/underthehood/flowP.html
    0 讨论(0)
  • 2020-12-16 12:36

    Bytecode is some sort of assembly language for the virtual machine. It is very common to have jump instructions in machine language. goto is a unconditional jump instruction.

    The Java compiler translates almost all control flow statements inside a method body into goto instructions.

    The goto keyword was probably reserved in Java to retain the option to add it to a later version in case it would have turned out that it's existence would have been critical. There is actually nothing wrong with goto from a machine point of view. It has got a bad reputation because it allows to write code that is very hard to read for a human. The Java language allows you to use break and continue with labels as a replacement for goto.

    0 讨论(0)
提交回复
热议问题