Java Reference
In-Depth Information
< Day Day Up >
Puzzle 7: Swap Meat
This program uses the compound assignment operator for exclusive OR. The technique that it
illustrates is part of the programming folklore. What does it print?
public class CleverSwap {
public static void main(String[] args) {
int x = 1984; // (0x7c0)
int y = 2001; // (0x7d1)
x ^= y ^= x ^= y;
System.out.println("x = " + x + "; y = " + y);
}
}
Solution 7: Swap Meat
As its name implies, this program is supposed to swap the values of the variables x and y . It you ran
it, you found that it fails miserably, printing x = 0; y = 1984 .
The obvious way to swap two variables is to use a temporary variable:
int tmp = x;
x = y;
y = tmp;
Long ago, when central processing units had few registers, it was discovered that one could avoid
the use of a temporary variable by taking advantage of the property of the exclusive OR operator ( ^ )
that (x ^ y ^ x) == y :
 
 
Search WWH ::




Custom Search