Feb 2, 2011

Best Way to Swap Values in Java

Though not all Java applications require variables to be swapped, but those which do require are not given proper thoughts about correct and optimized implementation.

Method-1: Using temporary Variable

The most common way to swap two values is by using a temporary variable as shown below:
int a=10,b=5,c;
c=a; (c=10,a=10,b=5)
a=b; (c=10,a=5,b=5)
b=c; (c=10,a=5,b=10)
If the use of temporary variable c is not allowed, then we have the following two options:


Method-2.1 : Using the addition and subtraction operations
int a=10,b=5;
a=a+b;
b=a-b;
a=a-b
The problem with the above solution is that the addition and subtraction can cause overflows. An overflow is a condition when the value of a variable is increased/decreased beyond the maximum/minimum value of that variable. Though the output of such a program may show that the variables have been swapped but it is not guaranteed as per Specification of various programming languages including Java.

Example Code:
package example.java;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a + b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a - b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = a - b;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}
Output:
After operation 1, a =  -394967298 b = 1899999999
After operation 2, a =  -394967298 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

Here we can see that the overflow had occurred after first arithmetic operation and hence the behaviour after that is unpredictable.

Method-2.2 : Using the addition and subtraction operations

Here is a way out avoid the arithmetic overflow while swapping variables using arithmetic operations.

Example Code:
package example.java;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a - b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a + b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = b - a;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}

Output:
After operation 1, a =  100000000 b = 1899999999
After operation 2, a =  100000000 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

The operation 3 in the above program should be noticed that it is a = b – a and not a = a - b

Method-3: Using the XOR operator

The XOR operator can also be used swap two variables using the logic shown below:
int a=10,b=5;
a=a^b;
b=a^b;
a=a^b
A program to justify the above solution is:


Example Code:
package example.java;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a ^ b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a ^ b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = a ^ b;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}


Output:

After operation 1, a =  101327104 b = 1899999999
After operation 2, a =  101327104 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

1 comment:

  1. Hi Sandeep,
    This reminds me one of questions asked during interviw "How do you swap two variables without using temp variable" , your post has answer of those by using addtion and XOR operation. keep the good work going.

    here I am putting some of my favorite interview questions which is increasingly getting popular on senior level java interview.

    deadlock in java
    Why String is immutable in Java
    Difference between HashMap and HashTable? Can we make hashmap synchronized
    ow to check if a thread holds lock on a particular object in Java
    How HashMap works in Java
    How get() method of HashMap works in JAVA

    Thanks
    Javin
    FIX Protocol tutorial

    ReplyDelete