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;
By writing your swap all in one statement, you are relying on side effects of the inner i ^= j
expression relative to the outer i ^= (...)
expression.
From the Java specificiation (15.26 Assignment Operators):
There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.
[...]
AssignmentOperator: one of = *= /= %= += -= <<= >>= >>>= &= ^= |=
You might want to consider the readability of the code. Perhaps it's best to e.g. put the code in a method called swap(), or do the actual swapping through the use of a temp variable:
int temp = i;
i = j;
j = temp;