Skip to main content
1 of 2
Olivier Grégoire
  • 14.4k
  • 3
  • 32
  • 56

Swap variables

You might want to swap int and long variables. The usual way is to have a temporary variable:

void swap(int a, int b) {
  int t=a;a=b;b=t;     //  16 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

But you can shorten it like this:

void swap(int a, int b) {
  a^=b^(b=a);          // 11 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

Even if you reuse a temporary variable, it's just shorter to write that code, no matter the length of each variable name.

Does work with short and byte but at the cost of casting.

Olivier Grégoire
  • 14.4k
  • 3
  • 32
  • 56