Write Java program to Swap two numbers using bitwise operator


This is a Java program that demonstrates swapping two numbers using bitwise operators. The program first declares two integer variables num1 and num2, and then prompts the user to input two numbers using the Scanner class.

It then uses the XOR (^) operator to swap the values of the two variables without using a temporary variable. The XOR operator works by comparing the corresponding bits of two numbers and returning a 1 if the bits are different, and a 0 if they are the same.

The program performs the swapping in three steps:

  • num1 = num1 ^ num2; // num1 now stores the XOR result of num1 and num2
  • num2 = num1 ^ num2; // num2 now stores the original value of num1
  • num1 = num1 ^ num2; // num1 now stores the original value of num2

Finally, the program outputs the swapped values of num1 and num2 using the printf method.

Note that the bitwise operator approach to swapping two numbers can be faster than the traditional method of using a temporary variable. However, it may also be less readable and more prone to errors if not used carefully.

Source Code

import java.util.Scanner;
public class SwapNum_BitwiseOperator
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int num1 = 0;
		int num2 = 0;
		System.out.printf("Enter the Number 1 : ");
		num1 = input.nextInt();
		System.out.printf("Enter the number 2 : ");
		num2 = input.nextInt();
 
		System.out.printf("Before Swapping Num1 : %d || Num2 : %d", num1, num2);
		num1 = num1 ^ num2;
		num2 = num1 ^ num2;
		num1 = num1 ^ num2;
		System.out.printf("\nAfter Swapping Num1 : %d || Num2 : %d", num1, num2);
	}
}

Output

Enter the Number 1 : 100
Enter the number 2 : 200
Before Swapping Num1 : 100 || Num2 : 200
After Swapping Num1 : 200 || Num2 : 100