Write a java program to swap two numbers using bitwise operators

Hey guys!! Welcome to flower brackets blog. Let’s learn how to write a java program to swap two numbers using bitwise operators.

Write a java program to swap two numbers using bitwise operators
Write a java program to swap two numbers using bitwise operators

Write a java program to swap two numbers using bitwise operators

First user enters two numbers as input. Next find bitwise xor for first two numbers and store in first variable.

Repeat the same operation of bitwise xor and store in second variable. Lastly bitwise operation is performed on first and second number and the output is stored in first variable.

Also read – swap two numbers in java using function

Here’s the java program to swap the contents of two numbers using bitwise XOR operation,

import java.util.Scanner;
public class SwapUsingBitwiseDemo 
{
public static void main(String[] args)
{
int a, b;
Scanner sc = new Scanner(System.in);
System.out.print("First number : ");
a = sc.nextInt();
System.out.print("Second number : ");
b = sc.nextInt();
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After Swapping - ");
System.out.println("First number : " + a);
System.out.println("Second number : " + b);
sc.close();
}
}

Output:

First number : 50
Second number : 100
After Swapping –
First number : 100
Second number : 50

Related Posts