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 swap two numbers using bitwise operator in java 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.

Also read – bitwise operators in java

Finally bitwise operation is performed on first and second number and the output is stored in first variable.

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.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;
      // 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 – swap two numbers without using third variable in java

Swap two numbers without using third variable and arithmetic operator

Now let’s learn how can we swap two numbers without using third variable and without using arithmetic operator,

public class SwapTwoNumbersWithoutThirdVariable 
{
   public static void main(String[] args) 
   {
      int number1 = 14;
      int number2 = 23;
      System.out.println("Before swapping two numbers without using third variable and arithmetic operator: ");
      System.out.println("Value of number1 is: " + number1);
      System.out.println("Value of number2 is: " + number2);
      number1 = number1 + number2;
      number2 = number1 - number2;
      number1 = number1 - number2;
      System.out.println("After swapping two numbers without using third variable and arithmetic operator: ");
      System.out.println("Value of number1 is: " + number1);
      System.out.println("Value of number2 is: " + number2);
   }
}


Output:

Before swapping two numbers without using third variable and arithmetic operator:
Value of number1 is: 14
Value of number2 is: 23
After swapping two numbers without using third variable and arithmetic operator:
Value of number1 is: 23
Value of number2 is: 14