Swapping of two numbers with third variable in Java

In this section you will learn how to swap two numbers in java using third variable. We will use three variable for swapping the numbers. In this program we are taking the value from user.

Swapping mean interchange of the values.

Let’s suppose a user will input two number as a ‘10’ and ‘20’ then we will perform swapping operation on it. We will use one temporary variable that is our third variable.

What is scanner function?

Scanner function is use to take the input from user in java.

How program will work?

Program of swapping two numbers in Java using third variable.


	import java.util.Scanner;

	class Swapping
	{
		public static void main(String arg[])
		{
			int num, num1, swap;
			Scanner sc = new Scanner(System.in);
			System.out.println("ENTER THE FIRST NUMBER:-");
			num = sc.nextInt();
			System.out.println("ENTER THE SECOND NUMBER:-");
			num1 = sc.nextInt();
			
			System.out.println("BEFORE SWAPPING OF TWO NUMBER:- "+num+" "+num1);
			
			swap = num;
			num = num1;
			num1 = swap;
			
			System.out.println("AFTER SWAPPING OF TWO NUMBER:- "+num+" "+num1);
		}
	}

Output:


	ENTER THE FIRST NUMBER:- 10
	ENTER THE SECOND NUMBER:- 20
	
	BEFORE SWAPPING OF TWO NUMBER:- 10 20
	AFTER SWAPPING OF TWO NUMBER:- 20 10

Advertisment

Post Your Comment