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

To swap two numbers using bitwise xor operator in java first user enters two numbers as input using nextInt() method of Scanner class.

java program to swap two numbers using bitwise operator

These two numbers are stored in two integer variables a and b. Then, find bitwise xor of two user entered numbers using bitwise xor operator.

Bitwise xor operator compares bits of two operands. If two operands are equal it returns 1 else 0 if they are not equal. Here’s the program to swap two numbers using bitwise xor operator.

import java.util.Scanner;
public class SwapUsingBitwiseDemo 
{
   public static void main(String[] args) 
   {
      int a, b;
      Scanner sc = new Scanner(System.in);
      System.out.println("First number : ");
      a = sc.nextInt();
      System.out.println("Second number : ");
      b = sc.nextInt();
      // xor operator java
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
      // swapping numbers in java
      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


Also read – polymorphism in java