Java Program to Swap Two Numbers Using Bitwise Operator
In Java, there are many ways to swap two numbers. Generally, we use either swap() method of the Math class or use a third (temporary) variable to swap two numbers. Except these two ways, we can also swap two numbers using the bitwise operator (XOR) and using division and multiplication.
In this section, we will focus on creating a Java program to swap two numbers using bitwise operator (^).
Using Bitwise Operator
Bitwise Operator: Bitwise XOR operator is used to swap two numbers. It is represented by the symbol (^). It compares bits of two operands and returns false or 0 if they are equal and returns true or 1 if they are not equal. The truth table of XOR operator is as follows:
We can use the bitwise XOR operator to swap two numbers without using the swap() method and third variable. We must follow the steps given below:
- Find the binary equivalent of given variables, say X and Y.
- Find X^Y and store it in x, i.e. X = X ^ Y.
- Again, find X^Y and store it in Y, i.e. Y = X ^ Y.
- Find X^Y and store it in X, i.e. X = X ^ Y.
- The numbers are swapped.
Now implement the above steps in an example and understand the swapping.
Example: Swap the variables X = 5 and Y = 9 using the bitwise operator.
Solution:
Step 1: Binary equivalent of the variables X and Y are:
X = 5 = 0101 and Y = 9 = 1001
Step 2: Find X = X ^ Y.
Step 2: Find Y = X ^ Y.
Step 3: Find X = X ^ Y.
We see that the variable X contains 1001 which is equivalent to 9 and Y contains 0101 which is equivalent to 5. Therefore, the variables X and Y are swapped.
X = 9 and Y = 5
Let’s implements the above logic in a Java program.
SwapTwoNumbersExample1.java
Output:
Enter the first number: 5 Enter the second number: 9 Before swapping: a = 5, b = 9 After swapping: a = 9, b = 5
Let’s create a program that swap two numbers using the function.
SwapTwoNumbersExample2.java
Output:
Before swapping x= 12, y= 34 After swapping x= 34, y= 12
Using Multiplication and Division
We can also swap two numbers using multiplication and division operator.
SwapTwoNumbersExample3.java
Output:
values before swapping: x = 10 y = 20 values after swapping: x = 20 y = 10