Swapping Two Variables in Java: Four Implementation Strategies
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);
}
}