Java Program to Swap Two Numbers Using Bitwise OperatorIn 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 OperatorBitwise 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:
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 DivisionWe 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 Next TopicJava Tutorial |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India