Java program to swap two numbers using bitwise operator

Let’s learn swapping numbers in java and 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 bitwise xor java program first user enters two numbers as input. Then, find bitwise xor for first two numbers and store in first variable.

Repeat same operation. Store bitwise xor in second variable. Finally 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 example program to swap number using bitwise operator,

// java bitwise xor
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();
      // xor operator java
      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