My professor recently said that although x = x + 1
and x++
will obviously give the same result, there is a difference in how they are implemented in the JVM. What does it mean? Isn't compiler like: hey, I see x++
so I will switch it to x = x + 1
and carry on?
I doubt there is any difference when it comes to efficiency, but I would be surprised if assembly would be different in those cases…
Best Answer
I guess your professor perhaps meant - the value of
x
afterx = x + 1
andx++
will be same. Just to re-phrase, as it seems to be creating confusion in interpreting the question.Well, although the value of
x
will be same, they are different operators, and use different JVM instructions in bytecode.x + 1
usesiadd
instruction, whereasx++
usesiinc
instruction. Although this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation. I've checked this againstjavac
compiler.For eclipse compiler, from one of the comment below from @Holger:
You can check the byte code using
javap
command. Let's consider the following class:Compile the above source file, and run the following command:
The code will be compiled to the following bytecode (just showing the
main
method):