Java Program to Swap Two Numbers With and Without Using Third Variable

You are currently viewing Java Program to Swap Two Numbers With and Without Using Third Variable

Java program to swap two numbers with and without using third variable

//Java program to swap two numbers.
import java.util.*;

class SwapTwoNumbers
{
	public static void main(String []s)
	{
		int a,b;
		//Scanner class to read value
		Scanner sc=new Scanner(System.in);

		System.out.print("Enter value of a: ");
		a=sc.nextInt();
		System.out.print("Enter value of a: ");
		b=sc.nextInt();

		System.out.println("Before swapping - a: "+ a +", b: " + b);
		////using thrid variable
		int temp;
		temp=a;
		a=b;
		b=temp;
		//////////////////////
		System.out.println("After swapping  - a: "+ a +", b: " + b);
	}
}
import java.util.*;

class SwapTwoNumbers
{
	public static void main(String []s)
	{
		int a,b;
		//Scanner class to read value
		Scanner sc=new Scanner(System.in);

		System.out.print("Enter value of a: ");
		a=sc.nextInt();
		System.out.print("Enter value of a: ");
		b=sc.nextInt();

		System.out.println("Before swapping - a: "+ a +", b: " + b);
		////without using thrid variable
		a=a+b;
		b=a-b;
		a=a-b;
		//////////////////////
		System.out.println("After swapping  - a: "+ a +", b: " + b);
	}
}

Output

Enter value of a: 10
Enter value of a: 20
Before swapping - a: 10, b: 20
After swapping  - a: 20, b: 10
Enter value of a: 10
Enter value of a: 20
Before swapping - a: 10, b: 20
After swapping  - a: 20, b: 10

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply