Given two numbers x and y. We have to write a Java Program to Swap the contents of two numbers using Bitwise XOR Operation.
Input 1: x = 5, y = 10
Output : x = 10, y = 5
Explanation :
1. x = x ^ y -> x = 15
2. y = x ^ y -> y = 5
3. x = x ^ y -> x = 10
Input 2: x = 15, y = 20
Output : x = 20, y = 15
The bitwise XOR operator(represented by ^) compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal. Let’s say we have two numbers x and y, so what actually x^y will do is that it will compare every corresponding bit of x and y, and if they are different, it will generate 1 as the output of that two bits(one of x and one of y) taken into consideration and if bits are same, then it will generate 0 as the output of two bits.
Below is the code implementation of the above approach:-
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int x = 5 , y = 10 ;
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println( "The value of x is " + x
+ " and the value of y is " + y);
}
}
|
OutputThe value of x is 10 and the value of y is 5