Thursday, December 24, 2015

Java Programming: Swap two integer values without using a temporary variable


Every time I had to take programming exam for a software developer position, this is one of the tricky questions I usually encountered: "How to swap two integer values without using a temporary variable?". The first time I had this question I spent about 45 minutes thinking about the solution until I gave up and thought that it was impossible to solve. Fast forward many years after, I am wiser now so I already know the solutions. It turned out that there are two possible ways to solve this tricky question.

Solution #1: Using Arithmetic Operator

public class SwapVariablesDemo1
{
  public static void main(String[] args)
  {
    int x = 1;
    int y = 2;
    
    System.out.println("Values before swapping: x = " + x + ", y = " + y);
    
    x = x + y; // x = 3, y = 2
    y = x - y; // x = 3, y = 1
    x = x - y; // x = 2, y = 1
    
    System.out.println("Values after swapping: x = " + x + ", y = " + y);
  }
}

Output:

Values before swapping: x = 1, y = 2
Values after swapping: x = 2, y = 1


Solution #2: Using XOR Bitwise Operator

Aside from the arithmetic solution, the more technical way to solve this problem is to use the XOR bitwise operator. The XOR bitwise operator returns 0 if both operands are the same and returns 1 if both operands are different (refer to the XOR truth table below).

X Y X ^ Y
0 0 0
0 1 1
1 0 1
1 1 0

public class SwapVariablesDemo2
{
  public static void main(String[] args)
  {
    int x = 1; // 0001 in binary
    int y = 2; // 0010 in binary
    
    System.out.println("Values before swapping: x = " + x + ", y = " + y);
    
    x = x ^ y; // x = 3 (0011), y = 2 (0010)
    y = x ^ y; // x = 3 (0011), y = 1 (0001)
    x = x ^ y; // x = 2 (0010), y = 1 (0001)
    
    System.out.println("Values after swapping: x = " + x + ", y = " + y);
  }
}

Output:

Values before swapping: x = 1, y = 2
Values after swapping: x = 2, y = 1

If you want to impress your future employer during your programming exam, then I suggest that you use the XOR bitwise solution provided that you can explain the logic behind it.

Now, try asking your fellow developers this question and find out how many of them know the solution :)

No comments:

Post a Comment