How to Swap Variables

Author: Tatyana Milkina

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 для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments