Java - Program to Swap Two Numbers Using Bitwise Operator
An intriguing method for exchanging two numbers in Java that does away with the requirement for a temporary variable is to use the bitwise operator. The XOR (^) bitwise operator is used in this method to swap the values. This is how it operates:
The Bitwise XOR Operator Explained
When two bits are compared, the XOR operator gives 1 if the bits are different and 0 otherwise.
For example:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
Using this property, we can swap two numbers without using an additional variable.
Steps to Swap Two Numbers Using Bitwise XOR
Step 1: a = a ^ b - This stores the XOR of a and b in a.
Step 2: b = a ^ b - This retrieves the original value of a and stores it in b.
Step 3: a = a ^ b - This retrieves the original value of b and stores it in a.
Java Program to Swap Two Numbers Using Bitwise Operators
Here's a simple Java program that demonstrates this concept:
Program:
import java.util.Scanner;
public class SwapUsingBitwise {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Read two numbers from the user
System.out.print("Enter the first number (a): ");
int a = scanner.nextInt();
System.out.print("Enter the second number (b): ");
int b = scanner.nextInt();
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Step 1: a = a ^ b
a = a ^ b;
// Step 2: b = a ^ b (original value of a)
b = a ^ b;
// Step 3: a = a ^ b (original value of b)
a = a ^ b;
// Output: Display the swapped values
System.out.println("After swapping: a = " + a + ", b = " + b);
scanner.close();
}
}