Sign in
Log inSign up

Java program to swap two numbers without using a third variable

Rohit Kumar's photo
Rohit Kumar
·Jul 14, 2021·

2 min read

Here is a java program to swap two numbers without using a third variable. To do so you can use basic mathematical operations like multiplication, division and addition, subtraction. See the Further Explanation:

Trick #1: Addition, subtraction A=A+B; B=A-B; A=A-B

Program #1: Swap two numbers without using third variable using addition and subtraction.

import java.util.*;
class swapnumbers
{
    public static void main(String args[])
    {
    int a,b;
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter two numbers to swap (a & b) : ");
    a=sc.nextInt();
    b=sc.nextInt();
    System.out.println( "Values before swapping:\nValue of a ="+a+"\nValue of b="+b); 
    a=a+b;
    b=a-b;
    a=a-b;
    System.out.println( "\nValues after swapping:\nValue of a ="+a+"\nValue of b="+b);
    }

Trick #2: Multiplication, Division. A=A X B; B=A/B; A=A/B;

Program #2: Swap two numbers without using third variable using Multiplication and division

import java.util.*;
class swapnumbers
{
    public static void main(String args[])
    {
    int a,b;
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter two numbers to swap (a & b) : ");
    a=sc.nextInt();
    b=sc.nextInt();
    System.out.println( "Values before swapping:\nValue of a ="+a+"\nValue of b="+b); 
    a=a*b;
    b=a/b;
    a=a/b;
    System.out.println( "\nValues after swapping:\nValue of a ="+a+"\nValue of b="+b);
    }
}

Trick #3: XOR Operation, A=A^B; B=A^B; A=A^B;

Program #3: Swap two numbers without using third variable : XOR operation trick.

import java.util.*;
class swapnumbers
{
    public static void main(String args[])
    {
    int a,b;
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter two numbers to swap (a & b) : ");
    a=sc.nextInt();
    b=sc.nextInt();
    System.out.println( "Values before swapping:\nValue of a ="+a+"\nValue of b="+b); 
    a=a^b;
    b=a^b;
    a=a^b;
    System.out.println( "\nValues after swapping:\nValue of a ="+a+"\nValue of b="+b);
    }
}

Trick #4: Basic logic: 1 Line Trick, A=A+B – (B=A);

Program #4: Swap two numbers without using third variable: Basic Logic; 1 Line trick.


import java.util.*;
class swapnumbers
{
    public static void main(String args[])
    {
    int a,b;
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter two numbers to swap (a & b) : ");
    a=sc.nextInt();
    b=sc.nextInt();
    System.out.println( "Values before swapping:\nValue of a ="+a+"\nValue of b="+b); 
    a=a+b-(b=a);
    System.out.println( "\nValues after swapping:\nValue of a ="+a+"\nValue of b="+b);
    }
}