Java program to swap two numbers using bitwise operators

Hey guys!! Welcome to flower brackets blog. Let’s learn java program to swap two numbers using bitwise operators.

java program to swap two numbers using bitwise operators

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 – swap two numbers in java using function

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

Related Posts