int x=1;
int y=2;
x ^= y ^= x ^= y;
I am expecting the values to be swapped.But it gives x=0 and y=1. when i tried in C language it gives the correct result.
int x=1;
int y=2;
x ^= y ^= x ^= y;
I am expecting the values to be swapped.But it gives x=0 and y=1. when i tried in C language it gives the correct result.
Your statement is roughly equivalent to this expanded form:
Unlike in C, in Java the left operand of a binary operator is guaranteed to be evaluated before the right operand. Evaluation occurs as follows:
You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:
This is a more compact version that also works:
But this is a truly horrible way to swap two variables. It's a much better idea to use a temporary variable.
Mark is completely correct about how it evaluates in Java. The reason is JLS §15.7.2., Evaluate Operands before Operation, and §15.7, which requires evaluation left to right:
It is equivalent (by §15.26.2, Compound Assignment Operators) to:
We evaluate left to right, doing both operands before the operation.
Note that it is undefined behavior in C, because you're modifying the same variable twice between sequence points.