Java Program to Swap Two Numbers Without Using Third Variable

Given two numbers, we have to swap the value of two numbers. Let A and B be the two input numbers, we have to interchange their values as follows:

Input
A = 5, B = 2
Output
A = 2, B = 5

Java program to swap two numbers without using third variable.

Algorithm to swap two numbers without using temporary variable
    Let A and B be the numbers we want to swap.
  • Add A and B and store the result in A(A = A + B).
  • Subtract B from A and store the result in B(B = A - B).
  • Subtract B from A again and store the result in A(A = A - B).
ALERT
The sum of the two integers may be more than the range of integer data type. In this case, you will get wrong result.

package com.tcc.java.programs;

import java.util.*;

public class SwapTwoNumbers {
    public static void main(String args[]) {
        int A, B;
  
        Scanner in = new Scanner(System.in);
        System.out.println("Enter First Integer(A)");
        A = in.nextInt();
        System.out.println("Enter Second Integer(B)");
        B = in.nextInt();
        
        // Swapping A and B without using third variable
        A = A + B;
        B = A - B;
        A = A - B;

        System.out.println("After Swapping");
        System.out.println("A = " + A + "\nB = " + B);
    }
}
Output
Enter First Integer(A)
4
Enter Second Integer(B)
6
After Swapping
A = 6
B = 4

Java program to swap two variables using third temporary variable

In this program, we are using a temporary variable to avoid integer range overflow problem as described above.

package com.tcc.java.programs;

import java.util.*;

public class SwapTwoNumbersThirdVariable {
    public static void main(String args[]) {
        int A, B, temp;
        
        Scanner in = new Scanner(System.in);
        System.out.println("Enter First Integer(A)");
        A = in.nextInt();
        System.out.println("Enter Second Integer(B)");
        B = in.nextInt();
        
        // Swapping A and B using a temporary variable
        temp = A;
        A = B;
        B = temp;
 
        System.out.println("After Swapping");
        System.out.println("A = " + A + "\nB = " + B);
    }
}
Output
Enter First Integer(A)
2
Enter Second Integer(B)
8
After Swapping
A = 8
B = 2

Recommended Posts
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Reverse a Number using Recursion
Java Program to Find LCM and GCD of Two Numbers
Java Program to Add Subtract Multiply and Divide Two Numbers
Java Program to Convert Decimal to Binary Numbers
Java Program to Make a Simple Calculator using Switch Statement
Java Program to Find Sum of Digits of a Number
Java Program to Print Prime Numbers between 1 to 100
Java Program to Print Armstrong Numbers Between 1 to N
Java Program to Find Largest of Three Numbers
Java Program to Find All Factors of a Number
All Java Programs