The issue is the order of evaluation:
See JLS section 15.26.2
First, the left-hand operand is evaluated to produce a variable. If
this evaluation completes abruptly, then the assignment expression
completes abruptly for the same reason; the right-hand operand is not
evaluated and no assignment occurs.
Otherwise, the value of the left-hand operand is saved and then the
right-hand operand is evaluated. If this evaluation completes
abruptly, then the assignment expression completes abruptly for the
same reason and no assignment occurs.
Otherwise, the saved value of the left-hand variable and the value of
the right-hand operand are used to perform the binary operation
indicated by the compound assignment operator. If this operation
completes abruptly, then the assignment expression completes abruptly
for the same reason and no assignment occurs.
Otherwise, the result of the binary operation is converted to the type
of the left-hand variable, subjected to value set conversion (§5.1.13)
to the appropriate standard value set (not an extended-exponent value
set), and the result of the conversion is stored into the variable.
So your expression does:
a^=b^=a^=b;
- evaluate
a
- evaluate
b^=a^=b
- xor the two (so the
a in step one does not have ^=b applied to it yet)
- store the result in
a
In other words, your expression is equivalent to the following java code:
int a1 = a;
int b2 = b;
int a3 = a;
a = a3 ^ b;
b = b2 ^ a;
a = a1 ^ b;
You can see that from the disassembled version of your method:
private static void swapDemo1(int, int);
Code:
0: iload_0
1: iload_1
2: iload_0
3: iload_1
4: ixor
5: dup
6: istore_0
7: ixor
8: dup
9: istore_1
10: ixor
11: istore_0