In this tutorial you will learn about the Java Program to swap two numbers using bitwise operator and its application with practical example.
In this tutorial, we will learn to create a Java Program to swap two numbers using bitwise operator using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Bitwise Operator.
Bitwise operator XOR is used to swap two numbers. It’s symbol is (^). It checks 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:
x = 5, y = 6
x = x ^ y -> x =11
y = x ^ y -> y = 5
x = x ^ y -> x = 6
Java Program to swap two numbers using bitwise operator
In this program we would swap two values using bitwise Operator .first of we would take a values from user and then swap them using bitwise Operator. Let’s have a look at Code.
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 |
// java Program to swap values using bitwise operator import java.util.Scanner; public class Swapping { public static void main(String args[]) { //declaring variables and taking values from user.. int num, num1; Scanner scanner = new Scanner(System.in); System.out.print("Enter first number:"); num = scanner.nextInt(); System.out.print("Enter second number:"); num1 = scanner.nextInt(); // swaping values using bitwise operator num = num ^ num1; num1 = num ^ num1; num = num ^ num1; scanner.close(); // Printing result.. System.out.println("Fisrt number after swaping :"+num); System.out.println("Second number after swapping:"+num1); } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- no,number= it will hold entered number.
- Sum= it will hold result of calculation.
After that we take a numbers from user and we will swap value using bitwise operator.
- First of all we find binary equivalent of given variables.( num and num1).
- Find num = num ^ num1.
- Again, find num1 = num ^ num1.
- Find num^num1 and store it in num
- i.e. num = num ^ num1.
- Numbers are swapped now.
As shown in image values of number are being swapped using Bitwise operator.
and then finally we will print swapped values of numbers.