Home »
Java Programs »
Java Basic Programs
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:
- Using third variable
Here, we will use a temporary variable to swap the numbers.
- 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
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 »