How to Use the Java XOR Operator to Your Advantage


java xor operator

*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.

The little-known Java XOR operator can be extremely useful when in need of a parity check or a number swap. Even though not the quickest, it’s definitely a reliable operator to use within simpler codes. Let’s see what it is and how it works:

What Is the Java XOR Operator?

XOR stands for “exclusive or” operator and is also sometimes called exclusive disjunction. The Java XOR operator is represented by ^, or carret. ^ is a bitwise operator, meaning an operator that works on the bit level. The XOR Java operator take 2 equally-sized bits and perform a logical exclusive OR comparison. If either bit is equal to 1, the operator returns 1. However, if both bits are equal to 1 or 0, the operator returns 0.

How Does the XOR in Java Work?

Let’s take 5^6 as an example of the Java XOR operator. In binary, 5 is 101 and 6 is 110. If we compare each bit and eliminate the digits that don’t match up, the Java XOR operator will return binary 11, or 3.

How to Use the Java XOR Operator to Your Advantage

One classic use of the XOR Java operator is swapping two numbers without using a temporary variable. The basic idea works like this:

x = x ^ y ;
y = x ^ y ;
x = x ^ y ;

After the second line, the y is now equal to the original value of X due to the associative property, and after the third command x is equal to the original value of y.

Here is a simple example:

public class IntegerSwap {

public static void main(String a[]){
int x = 5;
int y = 9;
System.out.println(“Original values:”);
System.out.println(“x equals: “+x);
System.out.println(“y equals: “+y);
x = x^y;
y =x^y;
x= x^y;
System.out.println(“New Values After Swap:”);
System.out.println(“x equals: “+x);
System.out.println(“y equals: “+y);
}

You could accomplish the same swap using subtraction, but that would be more likely to cause a stack overflow.

Recommended read: If you are interested in other useful operators you can use in Java, also check out our collection of (answered) Java interview questions! Plus, you may also be interested in reading a bit more about the XOR operator.

Conclusion

The XOR operator in Java, ^, is a bitwise operator that compares each bit in a number and returns 0 if the numbers are the same, and 1 if they aren’t the same. The end result is that digit columns that are the same are eliminated. ^ is a useful operator for swapping numbers and also for performing parity checks.

Recent Posts