Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Swap Two Numbers without using Temp Variable

5.00/5 (4 votes)
18 Feb 2012CPOL 29.6K  
You can do it with some XORs:int a = 25, b = 7;a = a ^ b;b = b ^ a;a = a ^ b;Or the same thing with some shorthand to make the code even harder to read:a ^= b;b ^= a;a ^= b;
You can do it with some XORs:

int a = 25, b = 7;

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

Or the same thing with some shorthand to make the code even harder to read:
a ^= b;
b ^= a;
a ^= b;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)