In this post of Java Program to Swap two numbers using Bitwise XOR Operator. we will write a java program to swaps two numbers using bitwise XOR operator. Before we go through the program, let’s see what is a bitwise XOR operator: A bitwise XOR compares corresponding bits of two operands and returns 1 if they are not equal and 0 if they are equal. For example:
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
num1 ^ num2 = 00011101
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0 if both bits are equal. In our case it would return 29 which is binary equivalent to 00011101
Now let’s write this in a Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.kkjavatutorials.client; import java.util.Scanner; /** * @author KK JavaTutorials *Java Program to Swap two numbers using Bitwise XOR Operator */ public class SwaptwoNumbersTest { public static void main(String[] args) { int number1 = 0; int number2 = 0; Scanner scanner = null; try { scanner = new Scanner(System.in); System.out.print("Enter first number:"); number1 = scanner.nextInt(); System.out.print("Enter second number:"); number2 = scanner.nextInt(); /* * Just to make you understand,I am going to enter value of first * number as 10 and second as 5. Binary equivalent of 10 is 1010 and * 5 is 0101 */ System.out.println("------------Before Swapping-----------------"); System.out.println("First Number = " + number1); System.out.println("Second Number = " + number2); // number1 becomes 1111 = 15 number1 = number1 ^ number2; // number2 becomes 1010 = 10 number2 = number1 ^ number2; // number2 becomes 0101 = 5 number1 = number1 ^ number2; System.out.println("------------After Swapping-----------------"); System.out.println("First Number = " + number1); System.out.println("Second Number = " + number2); } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } } } |
Sample output of above program::
1 2 3 4 5 6 7 8 |
Enter first number:10 Enter second number:5 ------------Before Swapping----------------- First Number = 10 Second Number = 5 ------------After Swapping----------------- First Number = 5 Second Number = 10 |
You may also like –
How to convert number to words in java
How to swap two numbers with or without temporary variable in java
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
Check whether a number is prime or not
Thanks for visiting blog. If you have any doubts or any suggestions to make please drop a comment.