Swapping variables means assigning the value of one variable to another programmatically. It is a very common and important operation in programming languages. In this shot, we are going to see how to swap two variables with and without the help of a third variable.
int a,b,c;c = a;a = b;b = c;
In the code above, a
and b
are the two variables that we want to swap. The third variable c
will help us to swap a
and b
.
class HelloWorld {public static void main( String args[] ) {// create and initialize variablesint no1, no2, no3;no1 = 10;no2 = 20;// print values before swappingSystem.out.println("Before swapping - no1: "+ no1 +", no2: " + no2);// swap numbersno3 = no1;no1 = no2;no2 = no3;// print values after swappingSystem.out.println("After swapping - no1: "+ no1 +", no2: " + no2);}}
To do this, we first add the values of the two variables that we want to swap and make the sum equal to a
. Then we get the value of b
by subtracting it from a
. Finally, we get the value of a
by obtaining the difference between b
and the previous value of a
.
int a,b;a = a + b;b = a - b;a = a - b;
class HelloWorld {public static void main( String args[] ) {// create and initialize variablesint no1, no2;no1 = 10;no2 = 20;// print values before swappingSystem.out.println("Before swapping - no1: "+ no1 +", no2: " + no2);// swap numbersno1 = no1 + no2;no2 = no1 - no2;no1 = no1 - no2;// print values after swappingSystem.out.println("After swapping - no1: "+ no1 +", no2: " + no2);}}