Skip to content
The Chat Archive
gemini-2.5-pro· Google LMArena Human Preference 140K

How do you swap two numbers without using a third variable in Java?

  1. User

    How do you swap two numbers without using a third variable in Java?

  2. Assistant

    Of course! This is a classic interview question. While using a third variable is the most readable and standard approach, you can swap two numbers without one using a couple of clever techniques.

    Here are the two most common methods in Java.

    Method 1: Using Arithmetic Operators (Addition and Subtraction)

    This method uses a series of additions and subtractions to store the combined value of both numbers in one of the variables and then unravel them.

    The Code

    public class SwapWithArithmetic {
        public static void main(String[] args) {
            int a = 10;
            int b = 20;
    
            System.out.println("--- Before Swap ---");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
    
            // Step 1: a becomes the sum of both numbers (a = 10 + 20 = 30)
            a = a + b; 
            
            // Step 2: b becomes the original value of a (b = 30 - 20 = 10)
            b = a - b; 
            
            // Step 3: a becomes the original value of b (a = 30 - 10 = 20)
            a = a - b; 
    
            System.out.println("\n--- After Swap ---");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
        }
    }
    

    How it Works

    Let's trace the values of a and b.

    • Initial State: a = 10, b = 20
    • a = a + b;: a is now 10 + 20 = 30. b is still 20. The variable a now holds the information of both original numbers.
    • b = a - b;: b is now 30 - 20 = 10. This calculation effectively subtracts the original b from the sum, leaving the original a.
    • a = a - b;: a is now 30 - 10 = 20. This subtracts the new value of b (which is the original a) from the sum, leaving the original b.

    Drawback

    This method can fail due to integer overflow. If a + b is larger than the maximum value for the integer type (e.g., Integer.MAX_VALUE), the sum will overflow and wrap around, leading to incorrect results.


    Method 2: Using the Bitwise XOR (^) Operator

    This is generally considered the best and safest method for swapping without a third variable because it avoids the overflow problem. It relies on the properties of the XOR operation.

    Key XOR Properties:

    1. x ^ x = 0 (A number XORed with itself is zero)
    2. x ^ 0 = x (A number XORed with zero is itself)
    3. x ^ y = y ^ x (Commutative)
    4. (x ^ y) ^ y = x (The key property for this swap!)

    The Code

    public class SwapWithXOR {
        public static void main(String[] args) {
            int a = 10; // Binary: 00001010
            int b = 20; // Binary: 00010100
    
            System.out.println("--- Before Swap ---");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
    
            // The magic happens here
            a = a ^ b;
            b = a ^ b;
            a = a ^ b;
    
            System.out.println("\n--- After Swap ---");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
        }
    }
    

    How it Works

    Let's trace the values using the variables themselves.

    • Initial State: a = original_a, b = original_b
    • a = a ^ b;: a now holds the result of original_a ^ original_b. b is unchanged.
    • b = a ^ b;: This translates to b = (original_a ^ original_b) ^ original_b. Because of property #4, this simplifies to b = original_a. The swap for b is complete!
    • a = a ^ b;: This translates to a = (original_a ^ original_b) ^ original_a. Because XOR is commutative, this is the same as a = (original_a ^ original_a) ^ original_b. This simplifies to a = 0 ^ original_b, which is a = original_b. The swap for a is complete!

    This method works flawlessly with any integer type and does not suffer from overflow issues.


    Summary and Recommendation

    MethodProsCons
    Using a Temp Variable (Standard)Extremely readable, works for all data types (including objects), no side effects.Uses one extra variable (negligible memory impact).
    Arithmetic (Add/Subtract)No extra variable.Less readable, can fail due to integer overflow.
    Bitwise XOR (^)No extra variable, does not overflow.Less readable for developers unfamiliar with bitwise operations.

    Which one should you use?

    • In real-world production code: Always use the temporary variable.

      int temp = a;
      a = b;
      b = temp;
      

      Code is written for humans to read and maintain. The clarity and obvious intent of the temporary variable method far outweigh the microscopic performance or memory gain of the other methods. Modern compilers and JIT (Just-In-Time) optimizers are so smart that they might optimize all three versions to the same underlying machine code anyway.

    • In a technical interview: Know all three methods. Explain the pros and cons of each. Start by saying you'd use a temp variable in production code for clarity, but then demonstrate your knowledge of the arithmetic and (especially) the XOR methods to answer the specific question asked. The XOR swap is the classic, "correct" answer to this puzzle.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.