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 Explaination : 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:-
The value of x is 10 and the value of y is 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.