Swap Two ints Without Using a Third Variable

Swap Two ints Without Using a Third Variable

Here’s an old trick from C, which carries over to Java. If you have two intsa and bwhose values you want to swap, the obvious way to do so is with a third, temporary variable:

int c = a;a = b;b = c;

It can be done without a temporary variable, however, using Java’s bitwise xor operator ^:

a = a^b;b = a^b;a = a^b;

The operator ^ produces a new int, each of whose bits is the result of xor-ing the two corresponding bits from the operands (1 if the bits are different, 0 otherwise). To see why the trick works, consider the single-bit case of a=1 and b=0.

a = a^b = 1 xor 0 = 1b = a^b = 1 xor 0 = 1a = a^b = 1 xor 1 = 0

Even though you initially overwrite the value of a, no information is lost; its encoding simply changes. In the case of larger (multi-bit) numbers, each pair of bits will be swapped in the same way, and so the entire int values are swapped.

Finally, the swapping code can be made even more succinct:

a ^= b ^= a ^= b;


Share the Post: