JAVA program to swap two numbers

JAVA program to swap two numbers

This JAVA program is to swap two numbers or exchange two numbers.

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

Just take a temporary variable and store the 1st value in it and then in variable a store the value of 2nd variable(b).

Then store the value of temp variable in 2nd variable.There you go you performed swapped operation successfully.

Dry Run of the Program

Let us take a=7 and b=8.

t=a  i.e. t=7

a=b i.e. a=8

b=t i.e. b=7

Now we get a=8 and b=7 , hence the numbers have been swapped.

Program

import java.util.*;

class swap
{
	public static void main(String args[])
	{
		int a,b,t;
		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);	
		t=a;
		a=b;
		b=t;
		System.out.println("The values after swap");
   	 	System.out.println("a = "+a+" b = "+b);	
	}
}

Output

Share Me!