Enter any two integer number as input. After that we first find bitwise XOR of first and second variables and store it in first variable. Now again we perform bitwise XOR operation of the same variables and store it in second variable. Finally bitwise XOR is performed on first and second variable and result is stored in first variable. Hence we get the swapped value as an output.
Here is the source code of the Java Program to Swap the Contents of two Numbers using Bitwise XOR Operation. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Swap_BitwiseXOR
public static void main(String args)
int m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
m = s.nextInt();
System.out.print("Enter the second number:");
n = s.nextInt();
m = m ^ n;
n = m ^ n;
m = m ^ n;
$ javac Swap_BitwiseXOR.java $ java Swap_BitwiseXOR Enter the first number:6 Enter the second number:7 After Swapping First number:7 Second number:6
Sanfoundry Global Education & Learning Series – 1000 Java Programs.