Guide For School logo Guide For SchoolICSE and ISC Resources

Swapping two numbers without using third variable [Method 1]

17 February 2015


This is the Java programming code written in BlueJ which swaps the values of two numbers without using any third variable.

This is the first method in which we have used the concept of Bitwise XOR operator which is indicated by a caret ( ^ ).

[Note: Lessons on Bitwise XOR operator will be added soon.]

Method 2 of swapping two numbers using without using any third variable and by using the concept of simple mathematical operations including addition and subtraction can be read from here: [Method 2]

Programming Code:

Java
/**
 * The class Swapping_Method1 takes 2 numbers as input and swaps their value without using any 3rd variable
 * This is Method 1
 * @author : www.guideforschool.com
 * @Program Type : BlueJ Program - Java
 */

import java.util.Scanner;
class Swapping_Method1
    {
        public static void main(String args[])
        {
        Scanner sc = new Scanner(System.in);
            int a,b;
            System.out.print("Enter the 1st no: ");
            a=sc.nextInt();
            System.out.print("Enter the 2nd no: ");
            b=sc.nextInt();

            System.out.println("-------------------------------");
            System.out.println("The numbers before swapping are");
            System.out.println("a = "+a);
            System.out.println("b = "+b);

            //Beginning of Swapping
            a=a^b;
            b=a^b;
            a=a^b;
            //End of Swapping

            System.out.println("-------------------------------");
            System.out.println("The numbers after swapping are");
            System.out.println("a = "+a);
            System.out.println("b = "+b);
        }
    }

Output:

Enter the 1st no: 25
Enter the 2nd no: 13
——————————-
The numbers before swapping are
a = 25
b = 13
——————————-
The numbers after swapping are
a = 13
b = 25

Working:

Initially a=25 and b=13,

Step 1: a=a^b gives, a=25^13
Now,
Binary equivalent of 25 = 11001
Binary equivalent of 13 = 01101
=======================
25^13 = 10100 (i.e. 20)
=======================
therefore, a=a^b gives, a=20

Step 2: b=a^b gives, b=20^13
Now,
Binary equivalent of 20 = 10100
Binary equivalent of 13 = 01101
=======================
20^13 = 11001 (i.e. 25)
=======================
therefore, b=a^b gives, b=25

Step 3: a=a^b gives, a=20^25
Now,
Binary equivalent of 20 = 10100
Binary equivalent of 25 = 11001
=======================
20^25 = 01101 (i.e. 13)
=======================
therefore, a=a^b gives, a=13

Hence, finally we have a=13 and b=25. [Swapping Done]

Tags and Categories

Wayback RecoveredGeneralGeneral