How to Swap Variables in Java - Quiz
Total: 5 questions
1. How do you swap the values of two variables using a temporary variable in Java?
How do you swap the values of two variables using a temporary variable in Java?
Introduce a temporary variable tmp that holds the value of the first variable while the second one is written into it: int tmp = a; a = b; b = tmp;. This is the simplest and most reliable approach: it works with any type (int, double, String, object references) and has no hidden traps. It is the one you should reach for by default.
2. How do you swap two integer variables without a third variable using arithmetic, and what is the danger of this approach?
How do you swap two integer variables without a third variable using arithmetic, and what is the danger of this approach?
Use addition and subtraction: a = a + b; b = a - b; a = a - b;. The danger is that the sum a + b can exceed the range of int (overflow). The final swap still comes out correct because the same wrap cancels out during subtraction, but relying on that in real code is a bad idea. For double and float the trick is unreliable due to precision loss, so in production you use the temporary-variable swap.
3. How does swapping two variables with XOR work, and what are its limitations?
How does swapping two variables with XOR work, and what are its limitations?
It uses the bitwise exclusive OR: a = a ^ b; b = a ^ b; a = a ^ b;. It works thanks to two properties of XOR: x ^ x == 0 and x ^ 0 == x. Unlike arithmetic, XOR has no overflow problem, but it works only for integer types. One gotcha: if you apply this swap to the same variable (for example arr[i] and arr[j] when i == j), it zeroes the value out.
4. Why does a swap(int x, int y) method not change the values of the variables in the caller?
Why does a swap(int x, int y) method not change the values of the variables in the caller?
Java always passes arguments by value: the method receives copies of the variables, not the variables themselves. The swap inside the method exchanges the copies x and y, while the originals a and b stay unchanged. A universal swap(int, int) method for two local variables is simply impossible in Java. The workaround is to pass a container — an array, a list, or a wrapper object — and modify its contents inside the method.
5. How do you swap two elements of an array or a list in Java?
How do you swap two elements of an array or a list in Java?
For an array a swap method works: it gets a copy of the reference, but that reference still points to the same object, so element changes are visible to the caller: int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;. For lists the standard library already ships Collections.swap(list, i, j), which exchanges two elements by their indices. For example, for the list [A, B, C] the call Collections.swap(list, 0, 2) yields [C, B, A].