Java exclusive or example: reverse an integer array 

Joined:
07/29/2009
Posts:
14

March 31, 2011 20:05:53    Last update: March 31, 2011 20:05:53
The Java exclusive or operator is ^. This example uses it to reverse an integer array:
public class ExclusiveOrExample {
    public static void main(String[] args) {
	int [] a = { 1, 2, 3, 4, 5, 6 };
	reverseArray(a);
	System.out.print(a[0]);
	for (int i = 1; i < a.length; i++) {
	    System.out.print(", " + a[i]);
	}
	System.out.println();
    }

    private static void reverseArray(int[] a) {
	int i = 0, j = a.length - 1;
	while (i < j) {
	    a[i] = a[i] ^ a[j];
	    a[j] = a[i] ^ a[j];
	    a[i] = a[i] ^ a[j];
	    i++;
	    j--;
	}
    }
}
Share |
| Comment  | Tags