Swapping two numbers using bitwise operator in Java

Java Program to Swap two numbers using Bitwise Operator

Swap two numbers using bitwise operator There are a number of methods to swap two numbers using Java. Today we will focus on swapping those numbers using a bitwise operator in java. In computers, arithmetic calculations such as addition, division, subtraction, multiplication etc are done at a bit level. To perform these calculations, we have bitwise operators such as OR(|), AND(&), XOR(^), complement(~), shift right (>>), shift left(<<) etc. Bitwise is an XOR operator that compares bits of two numbers. If the numbers are equal, it returns the output as 1. If the numbers are not equal, it returns the output as 0.

For example, if we take the binary output of say number 1 which is: 00000101 and binary output of number 5 is: 00001010. As we compare the outputs of these 2 binary numbers, we can conclude that they are not the same on comparison. Hence, the output for the above numbers will be 0. The other methods for swapping two numbers are by using the temp variable, using an array, using the third variable with the arithmetic operator, using temp with multiplication and division etc. Swapping in a process in which the values of two integer numbers are exchanged with each other.

Below is a program to understand how we can swap two numbers using Java. For this, we will use the nextInt() method of the Scanner class.

Swap two numbers using bitwise operator

import java.util.Scanner;
public class DeveloperHelps
public static void main(String args[])
int num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner.nextInt();
System.out.print("Enter second number:");
num2 = scanner.nextInt();
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
System.out.println("First number after swapping is:"+num1);
System.out.println("Second number after swapping is:"+num2);

The output of the above program for swapping two number using bitwise operator in java will be:

Enter first number: 160
Enter second number: 260
First number after swapping is: 260
Second number after swapping is: 160

Here we have used nextInt() method of Scanner class to swap two numbers in Java. We use scanner class to breakdown the input into small token values.To know more about scanner class, click here.

Leave a comment

Your email address will not be published. Required fields are marked *