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:
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
);goto
is thought to be a bad practice in programming/coding, because of realizing the 'spagetti' code and making worse the readability of code.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:
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.