Skip to content

Example: Swap two numbers without using a temporary variable

Roberto Fronteddu edited this page Jul 5, 2024 · 1 revision

Given two variables, x, and y, swap two variables without using a third variable.

The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ.

import java.io.*;

public class GFG {

    public static void main(String a[])
    {
        int x = 10;
        int y = 5;

        // Code to swap 'x' (1010) and 'y' (0101)
        x = x ^ y; // x now becomes 15 (1111)
        y = x ^ y; // y becomes 10 (1010)
        x = x ^ y; // x becomes 5 (0101)

        System.out.println("After swap: x = "+ x + ", y = " + y);
    }
}

We could also have done

x = x + y; // x becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
Clone this wiki locally