Swapping variables without temp variable

Before we have seen how to swap two variables with the use of temp. Now, it's time to see how to swap two variables without the use of a temporary variable. This is just easy if you take a look. It is all simple logic. The example below shows that. It is given with explanation of every statement for a better understand.




import java.util.*;
class SwappingWithoutTemp
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);

    System.out.println("Enter two numbers");
   
    int a=s.nextInt();
    int b=s.nextInt();

    a=a+b;
    b=a+b;
   
    a=b-a;
    b=-1*(a-b)-a;


    System.out.println("a is "+a+" b is "+b);
    }
}

Sample Output


Enter two numbers
50
40
a is 40 b is 50

Explaining the logic

I think you might be familiar with the basic statements such as reading the input from the user using Scanner class and storing them in variables. Fine, let us move on to the logic.

a=a+b; This statement adds up a and b and then puts it in a.
b=a+b; This statement adds up a and b and then puts it in b. By the time this statement executes the value of a is a+b. So, b=a+b will be equal to original a (the value that user enters into a)+(original b (the value that user enters into b)+(original b (the value that user enters into b)).

a=b-a; This statement subtracts a from the value of b.
By the time this statement executes, the value of b is a-b. So this statement gives, a+b-a which is nothing but b. For a better understand, this is much similar to (a+2b)-(a+b) where a,b are the original(initial) values of a and b i.e. the values that user enters into a and b respectively.

b=-1*(a-b)-a; Consider the sample output case. By the time the values will be,

a=40 since a is made equal to b just before this statement.
b=130 since b=a+b is executed after a=a+b is executed. When a=a+b is executed the value of a will be 90. and when b=a+b is executed the value will be 130 (i.e. a+b+b).
Now, -1*(a-b)-a gives 50 since a-b=-90 (40-130) and -1*(a-b) gives 90 and 90-a is equal to 90-40=50. In this way, we can easily swap variables even without the use of temporary variable. Simple is that. Feel free to drop a comment.

No comments: