Why swapping integer variable by XOR doesn't work in a single line?

后端 未结 5 2082
逝去的感伤
逝去的感伤 2020-12-16 17:59

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;

         


        
5条回答
  •  悲哀的现实
    2020-12-16 18:25

    The left-most i is being evaluated before it's changed.

    You can instead do:

    j ^= (i ^= j);
    i ^= j;
    

    Which is slightly less compact but works.

提交回复
热议问题