Swapping of two numbers without using third variable

This tutorial will teach you the methods for writing program to swap of two numbers. Swapping is used where you want to interchange the values.

Swapping of two numbers without using third variable

This tutorial will teach you the methods for writing program to swap of two numbers. Swapping is used where you want to interchange the values.

Swapping of two numbers without using third variable

Swapping of two numbers without using third variable

In this tutorial we will learn about swapping of two number in java without using third variable. This is simple program to swap two value using arithmetic operation Swapping of two numbers is most popular question asked in so many interviews for fresher level.  Swapping is nothing but exchanging the value of  two variables. This is done by arithmetic operation on variables to exchange the value. From the example below you get the explanation in the following steps:

a=10
b=20
Step 1:  a = a+b //Now a has value 30
Step 2:  b = a-b //Now b has value 10
Step 3:  a = a-b //Now a has value 20
a=20 // Now a has value 20
b=10 // Now b has value 10

 Example : Using this example we will explain you how to swap two variables without using the third variables. First we declare one class in which we take two integer variables a and b. After initialization of two variables performing addition and subtraction on the variables to swap the value of both. So from the example below you can get the code.

import java.io.BufferedReader;
import java.io.InputStream;
public class Swapping {

	public static void main(String args[])
	{
		int a=10;
		int b=20;
		System.out.println("Value of a before swapping = "+a);
	        System.out.println("Value of b before swapping = "+b);
		a=a+b;// a has now value 30
	        b=a-b;// b has now value 10
	        a=a-b;// a has now value 20
	    
	       System.out.println("");
	       System.out.println("Value of a after swapping = "+a);
	       System.out.println("Value of b after swapping = "+b);
	}
}

Output from the program

Download Source Code