JAVA program to swap two numbers using only two variables

JAVA program to swap two numbers without using a third variable/using only two variables

This JAVA program is to swap two numbers without using a third variable or using only two variables.

For example, if we have two numbers let us say a=7 and b=8,then on swapping we get a=8 and b=7. This a very simple and basic JAVA program.

Logic

We do not use a third variable.We first perform subtraction and store the value in the first variable. Then we perform addition and store the value in the second variable. Finally we perform another subtraction and store the value in the first variable.

Dry Run of the Program

Let us take a=7 and b=8

a=a-b i.e. a = 7 – 8 hence a = -1

b=a+b i.e. b = -1 + 8 hence b = 7

a=b-a i.e. a = 7 – (-1)  hence a = -8

We have successfully swapped two numbers without using a 3rd variable.

Program

/*Using only two variables*/
import java.util.*;

class swapN
{
	public static void main(String args[])
	{
		int a,b;
		Scanner sc = new Scanner(System.in);
	  	System.out.println("Enter the two numbers");
		a = sc.nextInt();
		b=sc.nextInt();		
		System.out.println("The values before swap");
   	 	System.out.println("a = "+a+" b = "+b);	
		
		a=a-b;
		b=a+b;
		a=b-a;
	
		//Can use this also
		/*a=a+b;		
		b=a-b;
		a=a-b;*/
	
		System.out.println("The values after swap");
   	 	System.out.println("a = "+a+" b = "+b);	
	}
}

Output

Share Me!