Java Program to Swap Two Numbers using Bitwise XOR Operation

This is a Java Program to Swap the Contents of two Numbers using Bitwise XOR Operation.

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.

  1. import java.util.Scanner;
  2. public class Swap_BitwiseXOR 
  3. {
  4.     public static void main(String args[])
  5.     {
  6.         int m, n;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter the first number:");
  9.         m = s.nextInt();
  10.         System.out.print("Enter the second number:");
  11.         n = s.nextInt();
  12.         m = m ^ n;
  13.         n = m ^ n;
  14.         m = m ^ n;
  15.         System.out.println("After Swapping");
  16.         System.out.println("First number:"+m);
  17.         System.out.println("Second number:"+n);
  18.     }
  19. }

Output:

$ 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.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.