Sorting Algorithms · Lesson 4/9
44%
⏱ 10–15 min

How to Swap Variables

When solving programming problems, you often need to swap the values of two variables. There are two common approaches for swapping values in Java:

Option 1: Swapping values using a temporary variable

You can introduce a temporary variable to hold one of the values temporarily during the exchange:

int tmp = a;
a = b;
b = tmp;

Example:

public class SwapExample1 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        int tmp = a;
        a = b;
        b = tmp;

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

Option 2: Swapping values without using a temporary variable

This method uses arithmetic operations (addition and subtraction) to perform the swap without a third variable:

a = a + b;
b = a - b;
a = a - b;

Example:

public class SwapExample2 {
    public static void main(String[] args) {
        int a = 3;
        int b = 5;

        a = a + b; // a = 8, b = 5
        b = a - b; // a = 8, b = 3
        a = a - b; // a = 5, b = 3

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

Note: The arithmetic method works only for numeric types and may cause integer overflow with very large values. The temporary variable method is safer and more readable in most cases.

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. Git & GitHub
9. OOP Basics
10. Lambda Expressions
11. Stream API
12. Inner Classes and Exceptions
‹ Previous lesson Next lesson ›