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

In swapping two numbers using bitwise 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.

Also read – bitwise operator in java

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

Also read – swapping of two numbers with 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


Also read – java program to swap two numbers without using third variable

Also read – java program to find smallest of three numbers using ternary operator

Also read – swap two numbers in java using function