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
// Java program to swap the elements using XOR Operator import java.io.*; class GFG { public static void main(String[] args) { int x = 5 , y = 10 ; // binary equivalent of 5 is 0101 // binary equivalent of 10 is 1010 // binary equivalent of x will become 1111 ie x=15 x = x ^ y; // binary equivalent of y will become 0101 ie y=5 y = x ^ y; // binary equivalent of x will become 1010 ie x=10 x = x ^ y; System.out.println( "The value of x is " + x + " and the value of y is " + y); } } |
The value of x is 10 and the value of y is 5