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:

Operation      and (&)          or (|)           xor (^)
Source       0  0  1  1       0  0  1  1       0  0  1  1
Mask         0  1  0  1       0  1  0  1       0  1  0  1
Result       0  0  0  1       0  1  1  1       0  1  1  0

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,

public class SwapDemo1
{
    public static void main(String[] args)
    {
        int a = +12345;
        int b = -67890;
        int hold;
        hold = a;
        a = b;
        b = hold;
        System.out.println("a=" + a + ", b=" + b);
    }
}
Download source code here.

But, surprisingly, xor used three times in the proper order has the same affect. For example,

public class SwapDemo2
{
    public static void main(String[] args)
    {
        int a = +12345;
        int b = -67890;
        a ^= b;
        b ^= a;
        a ^= b;
        System.out.println("a=" + a + ", b=" + b);
    }
}
Download source code here.

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!


Go to the articles index. Written by Bill Qualls. Copyright 2003 by Caliber Data Training 800.938.1222