Swapping two variables without using third variable. – Computer Sir Ki Class


Code Learning #JAVA#3780 siteicon   siteicon   siteicon  

Swapping two variables without using third variable.

Swapping of value between two integer variables without using the third variable.

Learning Objectives

  • Simple way to swap two variables without using the third temporary variable.

Source Code

TC++ #3780

Source Code

Alternate (?) :

Run Output

Before swapping: a = 10 b = 20
After swapping : a = 20 b = 10

Code Understanding

int a=10,b=20;
Variable a, b  are declared. No temp variable is taken. a is given initial value 10 and b as 20.

System.out.println(“Before swapping: a = “+a+” b = “+ b);
Here we print the values before swapping.

a=a+b; //First value  a is increased by amount b
b=a-b;  //The amount  b is subtracted from increased value of  a and transferred to b so that effectively b will now contain original value of a.
a=a-b; //The new b which now contains original a is subtracted from increased a which now contains (a+b), which means original b will come to a.

System.out.println(“After swapping : a = “+a+” b = “+b);
Here we print the values after swapping.


  • For smaller values this method may seem to work well with all types of data items but as the value size grows the logic may not work well. This is for the reason that container size requirement is double the individual value as values are to be added in the first step and put back into the first value. Just try with the following and you well understand that precision level differences may not result in exact swapping.
    float a=10.925f,b=20.150f;

Suggested Filename(s): SwapWoTemp.java


sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|