The simplest way to swap the values of two variables is to have a third variable that can temporarily hold the value of one variable while the other is being copied. This is very easy code, but a small problem is that we have to allocate extra memory. In these days of gigabytes of data, that is not a huge concern. But still it is useful to know a technique where you can achieve that.
So here are a couple of ways to do that I saw in a few places. I don’t have the name of the original author, I am assuming that it became common knowledge early. The first method uses addition, but if you have large values, then there is the chance of arithmetic overflow based on the result. The second method uses bitwise operations that avoid the “over-flaw” (sorry!)
public class Swap extends Object
{
public static void main(String args[])
{
int a = 123;
int b = 345;
System.out.println(a + " : " + b);
//Swapping using temporary variable : straight-forward method
int temp = a;
a = b;
b = temp;
System.out.println(a + " : " + b);
//Swapping using arithmetic operations : saves memory
a = a + b; //You can use a += b;
b = a - b;
a = a - b; //You can use a -= b;
System.out.println(a + " : " + b);
//Swapping using bitwise operations : avoids arithmetic overflow
a = a ^ b; //You can use a ^= b;
b = a ^ b; //You can use b ^= a;
a = a ^ b; //You can use a ^= b;
System.out.println(a + " : " + b);
}
}






