ADVERTISEMENT
ADVERTISEMENT

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

Swap two integer numbers in Java: Here, we will input two integer numbers and swap them through two methods 1) Using third variable and 2) without using third variable.

Given two integer numbers and we have to swap them with and without using third variable.

Swapping of two numbers program is very common and important program, Here we are implementing this program in Java using two methods:

  1. Using third variable
    Here, we will use a temporary variable to swap the numbers.
  2. Without using third variable
    Here we will not use any temporary variable to swap the numbers.

Consider the programs:

1) Swapping of numbers 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);
	}
}

Output

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

2) Swapping of numbers without using third variable

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

Java Basic Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.