Is it possible to write swap method in Java? [duplicate]

While it is not possible to write a function that simply swaps two variables, it is possible to write a helper function that allows you to:

  • Swap two variables using only one statement
  • Without temporary variables in the caller’s code
  • Without ‘boxing’ primitives
  • With a few overloads (one of them using generics), it works for any type

That’s how you could do it:

int returnFirst(int x, int y) {
    return x;
}
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. You assign the result to a

If returnFirst is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)). Use this to impress your friends and confuse your enemies 🙂

Leave a Comment