Java Interview Questions ยท Coding Problems

Swap Two Numbers Without a Third Variable

Learn a classic programming trick to swap the values of two integer variables without using a temporary variable. This lesson explores the arithmetic approach.

SwapNumbers.java

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        // Swapping logic starts here
        a = a + b; // a now becomes 30
        b = a - b; // b becomes 30 - 20 = 10
        a = a - b; // a becomes 30 - 10 = 20

        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}

Step by step

  1. The program starts execution inside the main method.
  2. An integer variable a is declared and initialized with the value 10.
  3. Another integer variable b is declared and initialized with the value 20.
  4. The current values of a and b are printed to the console before the swap.
  5. First step of the swap. We add b to a. The variable a now holds the sum of the original two numbers. a becomes 10 + 20 = 30.
  6. Second step. We subtract the original value of b from the new value of a. b becomes 30 - 20 = 10. Now, b holds the original value of a.
  7. Final step. We subtract the new value of b from the current value of a. a becomes 30 - 10 = 20. Now, a holds the original value of b. The swap is complete.
  8. The swapped values of a and b are printed to the console.
  9. The main method finishes execution, and the program terminates.