Java program to swap two numbers using bitwise operator

Let’s learn java program to swap two numbers using bitwise operator.

java program to swap two numbers using bitwise operator

Java program to swap two numbers using bitwise operator

In this java program first user enters two numbers as input. Then find bitwise xor for first two numbers and store in first variable.

Repeat the same operation store bitwise xor in second variable. Lastly bitwise operation is performed on first and second number and the output is stored in first variable.

Also read – preface to java virtual machine and architecture

Here’s the java program to swap the contents of two numbers using bitwise XOR operation,

import java.util.Scanner;
public class SwapUsingBitwiseDemo 
{
   public static void main(String[] args) 
   {
      int a, b;
      Scanner sc = new Scanner(System.in);
      System.out.print("First number : ");
      a = sc.nextInt();
      System.out.print("Second number : ");
      b = sc.nextInt();
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
      System.out.println("After Swapping - ");
      System.out.println("First number : " + a);
      System.out.println("Second number : " + b);
      sc.close();
   }
}

Output:

First number : 50
Second number : 100
After Swapping –
First number : 100
Second number : 50