Alex Rivera | Logout

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

Asked 2012-07-04T08:02:24.147
11

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?

Edit
Report

1 Answer

1

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.

answered 2012-07-04T08:43:04.893

Your Answer