Swap Two Numbers

Swap the values of two variables using a temporary variable.

JavaBeginner
Java
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

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

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

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

Output

Before swap: a = 5, b = 10
After swap: a = 10, b = 5

We use a temporary variable to store one value while we perform the swap:

temp = a → a = b → b = temp