Java Program to Swap integer numbers using bit wise XOR operator


April 20, 2022, Learn eTutorial
942

Here we are explaining how to write a java program to swap two numbers using bitwise XOR operator.

What is a bitwise XOR operator?

There are mainly six bitwise operators.

  • &
  • |
  •  ^
  •  ~
  • <<
  • >>

The bitwise operators perform bit-level operations. The bitwise XOR operator ^, compare the corresponding bits of n1 and n2 (n1^ n2), if the corresponding bits are equal then it will return 1.Else return 0.

How to implement the java program to swap two numbers using a bitwise operator?

First, we have to declare the class Swap. Declare the variables n1,n2 as integers. Read the numbers into n1 and n2. Then swap the numbers using the bitwise XOR operator as  

   n1 = n1 ^ n2;
   n2 = n1 ^ n2;
   n1 = n1 ^ n2;

Then display n1 and n2 using System.out.println() function.

suppose n1 as 10 and n2 as 2.

Then   n1 = n1 ^ n2; becomes 1010 ^ 0010=0111

           n2 = n1 ^ n2; becomes 0111 ^ 0010=1010

            n1 = n1 ^ n2;  becomes 0111 ^ 1010=0010

Now, n1=0010 means 2 and n2=1010 means 10.

ALGORITHM

STEP 1: Declare the class Swap with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variable n1,n2 is an integer.

STEP 4: Read the first number into n1.

STEP 5: Read the second number into n2.

STEP 6: Then assign n1=n1^ n2,n2=n1 ^ n2,n1=n1 ^ n2.

STEP 7: Then display the numbers after swapping as n1 and n2 using System.out.println() function.

Java Source Code

                                          import java.util.Scanner;
public class Swap{
    public static void main(String args[]){
        int n1,n2;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number:");
        n1= sc.nextInt();
        System.out.println("Enter the second number:");
        n2 = sc.nextInt();
         sc.close();
        n1 = n1 ^ n2;
        n2 = n1 ^ n2;
        n1 = n1 ^ n2;
      
        System.out.println("The First number after swapping is "+n1);
        System.out.println("The Second number after swapping is "+n2);
    }
}
                                      

OUTPUT

Enter the first number:5
Enter the second number:6
The First number after swapping is 6
The Second number after swapping is 5