I want to swap the value of two integer variables in java using the XOR operator.
This is my code:
int i = 24;
int j = 17;
i ^= j;
j ^= i;
i ^= j;
System.out.println("i : " + i + "\t j : " + j);
It will work fine but the following equivalent code doesn’t work:
int i = 24;
int j = 17;
i ^= j ^= i ^= j;
System.out.println("i : " + i + "\t j : " + j);
Output is like this:
i : 0 j : 24
First variable is zero! What’s wrong with Java?
According to Java specification (Java 7 specification), Section 15.26.2 (page 529).
According to Section 15.7 Evaluation Order (Page 423) (emphasis mine):
Described in more details in Section 15.26.2 (page 529):
An example in the documentation
So the expression in the question is re-written and grouped as:
Left-hand operands are evaluated:
Since the value of
iis not "updated" as expected, it will cause the value ofito get 0 when24is swapped toj.