Swap Two Numbers Using XOR Operator in Java



In this article, we will learn how to swap two numbers using the XOR bitwise operator in Java. The XOR operator is a powerful tool that allows you to perform bitwise operations, and one of its interesting properties is that it can be used to swap two variables without using a temporary variable. This method is efficient and can be used when you need a fast swapping mechanism.

Problem Statement

Given two integers, write a Java program to swap their values using the XOR operator.
Input
Two integers are provided by the user.
Output
The values of the two integers after swapping.

Steps to swap two numbers using the XOR operator

The following are the steps to swap two numbers using the XOR operator

  • Import the Scanner class from the java.util package for user input.
  • Declare two integer variables to hold the values of the numbers.
  • Use the XOR operator in three steps to swap the values:
  • XOR the two numbers and store the result in one of the variables.
  • XOR the updated variable with the second number and store the result in the second variable.
  • In the end, XOR the updated first variable with the updated second variable to complete the swap.
  • Print the swapped values.


Java program to swap two numbers using XOR operator

The following is an example of swapping two numbers using XOR operator

import java.util.Scanner;
public class ab31_SwapTwoNumberUsingXOR {
   public static void main(String args[]) {
      int a, b;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a value:");
      a = sc.nextInt();
      System.out.println("Enter b value:");
      b = sc.nextInt();
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
      System.out.println("Value of the variable a after swapping: " + a);
      System.out.println("Value of the variable b after swapping: " + b);
      sc.close(); 
   }
}

Output

Enter a value :
55
Enter b value :
64
Value of the variable a after swapping : 64
Value of the variable b after swapping : 55

Code Explanation

In this program, we use the XOR operator to swap two integers without a temporary variable. The bitwise XOR modifies a and b, swapping their values. The program prints the swapped values using System.out.println, showcasing efficient bitwise operations and primitive data types.
Updated on: 2024-11-05T22:02:32+05:30

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements