Java Program to Swap Two Variables Using X-OR Operation

Java program to swap two variables using x-or operation can be implemented by using a bit-wise operator like x-or. Swapping of two numbers means the exchanging of values between them.






1. Java Program & output of to swap two Numbers using X-Or Operation

Code has been copied
/*******************************************
        alphabetacoder.com
 Java program to swap numbers without third
 variable but using bit-wise operator X-OR
********************************************/

import java.util.Scanner;
public class Swap {
    public static void main(String args[]) {
        // declare variables
        int num1, num2;
        // declare an instance of Scanner class
        Scanner sc = new Scanner(System.in);

        // take input
        System.out.print("Enter two numbers = ");
        num1 = sc.nextInt();
        num2 = sc.nextInt();
        System.out.print("Before swapping: number1  = " + num1 + " and number2 = " + num2 + "\n");

        //do swapping using ^ (x-or)
        num1 = num1 ^ num2;
        num2 = num1 ^ num2;
        num1 = num1 ^ num2;

        System.out.print("After swapping: number1 = " + num1 + " and number2 = " + num2 + "\n");
    }
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5