Saturday, April 30, 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.

package com.vaani.swap.subtraction;
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

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

Thank you

No comments:

Post a Comment

Chitika