How to Swap Two Numbers in Java

Swapping two number is easy when you use a temporary variable. The following Java programs swaps two numbers using a temporary variable of the same type.

// Java program to swap numbers using temporary variable
public class SwapNumbersWithTemp {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("a="+a+",b="+b);

        int temp = a;
        a = b;
        b = temp;
        
        System.out.println("a="+a+",b="+b);
    }
}

The following program swaps two numbers without using a temporary variable. It uses addition and subtraction to move values around.

// Example: Java program to swap numbers without temp variable
public class SwapNumbersWithoutTemp {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("a="+a+",b="+b);

        a = a + b; // a is now a+b
        b = a - b; // b is now a
        a = a - b; // a is now b
        
        System.out.println("a="+a+",b="+b);
    }
}

The following program swaps numbers using a function without explicit temporary variables. This example works because the value of the b actually creates an implicit temporary variable during the method invocation.

// Swap numbers without temporary variable - Java example
public class SwapNumberWithFunction {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("a=" + a + ",b=" + b);

        a = getB(b,b=a);

        System.out.println("a=" + a + ",b=" + b);
    }
    
    public static int getB(int b,int a) {
        return b;
    }
}