by Neal R. Wagner
Copyright © 2002 by Neal R. Wagner. All rights reserved.
NOTE: This site is obsolete. See book draft (in PDF):
The code below shows how xor can be used to interchange data elements.
// Xor.java: test xor function ^ for interchanges
public class Xor {
// main function to try out Base class
public static void main (String[] args) {
int a = 123456789, b = -987654321;
printThem(a, b);
// interchange a and b
a = a^b;
b = a^b;
a = a^b;
printThem(a, b);
a = 234234234; b = -789789789;
printThem(a, b);
// interchange a and b
a ^= b;
b ^= a;
a ^= b;
printThem(a, b);
} // end of main
private static void printThem(int a, int b) {
System.out.println("a: " + a + ", \tb: " + b);
}
}
/* Output:
a: 123456789, b: -987654321
a: -987654321, b: 123456789
a: 234234234, b: -789789789
a: -789789789, b: 234234234
*/