Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
May 9, 2003

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 = 1
b = a^b = 1 xor 0 = 1
a = 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;
Matthew Johnson
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date