Hi!
I think you are wrong Vicken.
First the operators preference is different that you have said. Please look at this link
Java Operators, Precedence, and Associativity and you will see that the assigment operator is the lowest one in priority.
Now i will try to explain what means i = i++ and i = ++i;
a) i = i++;
1. the right i is evaluated and its value is stored to be used in the operation (the assigment)
2. the right i is incremented by one and the value is assigned to the right variable i
3. finally the left variable i is assigned the value of the operation (calculated in the first step)
b) i = ++i;
1. the right i is incremented by one and the value is assigned to the right variable i
2. the right i (that has been previously incremented) is evaluated and its value is stored to be used in the operation
3. finally the left variable i is assigned the value of the operation (calculated in the second step)
if you would like to be sure i can advice you to use the "javap" command
Finally, we can try this program again
1. the = operator is always the last operator evaluated so we start evaluating ++x + x++ and we start evaluating from left to right!
2. ++x increments the value of x that now is 11 and this value will be used in the + expression
3. x++ increments the value of x but before that the value of x will be stored to be used in the + expression (so the value of x before incremented --> 11 will be used in the + expression and after the storage the value of x is incremented by one... now x = 12)
4. the + expression is evaluated--> 11 + 11 = 22 (not 12 + 10 = 22!!!)
Here you can see the bytecode:
Compiled from test.java
class tests.test extends java.lang.Object {
tests.test();
public static void main(java.lang.String[]);
}
Method tests.test()
0 aload_0
1 invokespecial #1 <Method java.lang.Object()>
4 return
Method void main(java.lang.String[])
0 bipush 10 -> puts 10 in the stack
2 istore_1 -> stores the stack value (10) in the local variable 1
3 iinc 1 1 -> increments the local variable 1 by 1 (++x) --> x=11
6 iload_1 -> puts the local variable 1 in the stack (value=11)
7 iload_1 -> puts the local variable 1 in the stack (value=11) before it is incremented
8 iinc 1 1 -> increments the local variable 1 by 1 (x++) --> x=12
11 iadd -> the + operator is evaluated getting the two values from the stack and the result is putted in the stack (11 + 11 = 22)
12 istore_1 -> stores the stack value (22) in the local variable 1 (now x = 22)
13 getstatic #2 <Field java.io.PrintStream out>
16 iload_1
17 invokevirtual #3 <Method void println(int)>
20 return
And here you have got the link i use to understand the bytecode commands
JVM reference Hope it helps!