Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Swapping Two Variables in Java: Four Implementation Strategies

Tech Apr 18 61

Temporary Varible Method

The conventional approach utilizes an auxiliary storage location to facilitate the exchange. This technique offers optimal readability and avoids numeric boundary issues.

public class BufferSwap {
    public static void main(String[] args) {
        int alpha = 5, beta = 10;
        int buffer = alpha;
        alpha = beta;
        beta = buffer;
        System.out.println("alpha=" + alpha + ", beta=" + beta);
    }
}

Arithmetic Summation

Eliminate auxiliary storage by leveraging addition and subtraction operations. Note that this approach risks integer overflow when operating on large values near the int maximum.

public class SumDifferenceSwap {
    public static void main(String[] args) {
        int valueA = 5, valueB = 10;
        valueA = valueA + valueB;
        valueB = valueA - valueB;
        valueA = valueA - valueB;
        System.out.println("valueA=" + valueA + ", valueB=" + valueB);
    }
}

Bitwise XOR Exchange

Exploit the mathematical property that any number XORed with another number twice returns the original value. This method circumvents overflow concerns present in arithmetic aproaches.

public class BitwiseSwap {
    public static void main(String[] args) {
        int m = 5, n = 10;
        m = m ^ n;
        n = m ^ n;
        m = m ^ n;
        System.out.println("m=" + m + ", n=" + n);
    }
}

Output Reordering

For display purposes only, reverse the varible positions within the print statement. This technique modifies presentation without altering the actual memory values.

public class PrintSwap {
    public static void main(String[] args) {
        int first = 5, second = 10;
        System.out.println("first=" + second + ", second=" + first);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.