Google News
logo
Java Program to Swap two numbers using Bitwise XOR Operator
The following example of Java program to swap two numbers using Bitwise XOR Operator :
Program :
import java.util.Scanner;

public class SwapTwoNumbersXOR {

    public static void main(String[] args) {

        int x, y;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the value of x: ");
        x = in.nextInt();

        System.out.println("Enter the value of y: ");
        y = in.nextInt();

        System.out.println("Before swapping: ");
        System.out.println("x = " + x + ", y = " + y);

        // XOR swap algorithm
        x = x ^ y;
        y = x ^ y;
        x = x ^ y;

        System.out.println("After swapping: ");
        System.out.println("x = " + x + ", y = " + y);
    }
}
Output :
Enter the value of x: 
36
Enter the value of y: 60
Before swapping: 
x = 36, y = 60
After swapping: 
x = 60, y = 36
Explanation :

* We take two variables 'x' and 'y' and take input for them from the user.

* We then print the values of 'x' and 'y' before swapping.

* We use the XOR swap algorithm which uses the bitwise XOR operator to swap the values of 'x' and 'y'.

* We then print the values of 'x' and 'y' after swapping.