Write a Java program to swap two variables without using a third variable.

Two numbers can be swapped without a temporary variable using either arithmetic (addition and subtraction) or the bitwise XOR operator.

Key Points

public class SwapWithoutTemp {

    public static void main(String[] args) {
        int a = 10, b = 25;

        // 1. Using addition and subtraction
        a = a + b;   // 35
        b = a - b;   // 10
        a = a - b;   // 25
        System.out.println("After arithmetic swap: a = " + a + ", b = " + b);

        // 2. Using XOR (swaps them back)
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println("After XOR swap: a = " + a + ", b = " + b);
    }
}

Output

After arithmetic swap: a = 25, b = 10

After XOR swap: a = 10, b = 25

Good to Know

Java passes primitives by value, so a swap(int a, int b) method cannot swap the caller's variables. To swap inside a method you need an array or an object holding the values.

Show both versions and point out the overflow risk of the arithmetic one; that shows you know why XOR exists, not just the trick itself.

Interview Tip

A concise interview answer is

I can swap with arithmetic, a = a + b; b = a - b; a = a - b, or with XOR, a ^= b; b ^= a; a ^= b. XOR avoids overflow, but both break if the two values share the same location, so in production I would just use a temporary variable.

Last updated: 11 November 2026

Previous question: Write a Java program to reverse a string without using built-in reversal methods such as reverse().

Next question: Write a Java program to count the frequency of each word in a string using a HashMap.

More Java Coding Questions interview questions

All Java Coding Questions questions