Write a java program to swap two numbers using Bitwise XOR Operation

Here's a Java program that swaps two numbers using bitwise XOR operation: 

 

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5; // initialize first number
        int b = 10; // initialize second number

        System.out.println("Before swapping:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);

        // swap the numbers using bitwise XOR operation
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

        System.out.println("After swapping:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

In this program, we first initialize two variables a and b with the values we want to swap. We then perform the swap operation using bitwise XOR.

The basic idea behind using XOR for swapping two numbers is that XOR of two equal numbers is 0. By performing XOR operations on a and b, we can cancel out the original values of a and b and get the swapped values.

The program outputs the values of a and b before and after the swap.

Submit Your Programming Assignment Details