April 2003 Technical Tip – Using Exclusive Or to Swap Integers in Java
The Java programming language contains bit operations and (&), or (|), and exclusive or (^). Recall that bit operations work as follows:
The exclusive or (xor) is probably the operation programmers are least familiar with. The result is on if one, but not both, bits are on. As most assembly language programmers will tell you, the xor operation can be used to swap fields!
Typically, an attempt to swap two fields requires a third "holding" field. For example,
But, surprisingly, xor used three times in the proper order has the same affect. For example,
Two caveats: First, the ^ operator can be used with integers (byte, char, short, int, and long) only. Second, the two fields being swapped must the same type; that is, both byte, both short, etc.
So we see that what's old is new again. We at Caliber Data Training are pleased to offer high quality training in the old (COBOL, PL/I, Assembly) and the new (Java, C++) And we are confident that your legacy programmers will benefit from learning Java from instructors who speak their language! We hope you will consider us when deciding upon a training provider!