Java – x = x equals x = 2x 1: why?
The question is just curiosity: I want to know what the value of some int x is after the x = x line
int x=10; x+=++x; System.out.println(x);
It prints out:
21
After testing with some other values, it seems to be equivalent to x = 2x 1 Why? Is this line interpreted by the compiler as a byte operation? (by the way, x = x seems to be equal to x = 2x)
I don't think this is what I used in the project, but I'd like to know why I got this result
Thank you for any explanation or hint
Editor: first of all, thank you for your answer
I know how the = operator works, as well as X and X, but for some reason (completely logical and obvious) the result seems strange to me. I should have considered it. Sorry for your time!
Solution
Its calculation method is
>Step 1: x = x > Step 2: change to x = 10 (increment x) 11 > Step 3: the final result is stored in X, i.e. 21
This is proof that:
I created a mainclass as follows:
public class MainClass{ public static void main(String...s){ int x = 10; x += ++x; } }
Then use javap - C mainclass to check the bytecode
public static void main(java.lang.String...); Code: 0: bipush 10 // push 10 onto stack 2: istore_1 // store 10 in local variable 1 3: iload_1 // load local variable 1 (Now 10) back to stack 4: iinc 1,1 //increment local variable 1 by 1 7: iload_1 // load local variable 1 (Now 11) back to stack 8: iadd // add top 2 variable on stack ( 10 and 11) 9: istore_1 // store 21 to local variable 1 10: return }