Swap Two Values in Java: Explanation & Practice

Swap the values of two variables

Problem summary

You have two integer variables a=10 and b=20. Swap their values so a becomes 20 and b becomes 10.

Starter code

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        
        // Swap values here (without using a third variable)
        
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Expected output and test cases

  • Swap a and b values
    a = 20
    b = 10

Hints

  1. You can swap without a temp variable using arithmetic
  2. Try: a = a + b, then b = a - b, then a = a - b
  3. Or use XOR: a = a ^ b; b = a ^ b; a = a ^ b;

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler