Introduction

XOR operator is one of the bitwise operators in Java. The XOR (also known as exclusive OR) takes two inputs and outputs accurately only if both inputs are different. The best use of the XOR operator is in such a condition when both of the given inputs cannot be true at the same time.

This article will talk about the Java XOR operator, specifically, how the XOR operation can be used and how it can be implemented in Java.

 

Bitwise operators in Java

Unlike the simple arithmetic operators like (+, /, -, *, <, >, =) bitwise operators perform individual bits of a value. The bits are constantly evaluated, starting from left to right. The bitwise operators are used with primitive data types in Java, including int, byte, short, long, float, double, boolean, and char, but they cannot be used with String type.

new java job roles

Java XOR operator

For starters, the XOR operator takes two boolean operands as inputs and returns true if only if the operands are different. Thus, the output will be false if both operands are true or false.

As mentioned earlier, the XOR operator is commonly used in such conditions when the user has to ensure that the two conditions are not true or false simultaneously.

 

The following table shows all the possible inputs and their respective outputs for X (A XOR B):

A B X = A XOR B
FALSE FALSE FALSE
FALSE TRUE TRUE
TRUE FALSE TRUE
TRUE TRUE FALSE

This table would look very similar to the OR operator except for the last result because XOR (exclusive-OR) is a variation of the OR operator.

 

Implementation of XOR operator in Java

The XOR operator is denoted by a carrot (^) symbol in Java. It is implemented like any other operator; you need to use it appropriately and according to the syntax.

 

The code below demonstrates the proper syntax and the implementation of the all four possibilities in Java:

01. public class XOR_example {
02.   public static void main(String[] args) {
03.      boolean A = false;
04.      boolean B = false;
05. // First Case
06.      boolean AXorB = A ^ B;
07.      System.out.println("false XOR false: "+AXorB);
08. // Second Case     
09.      A = false;
10.      B = true;
11.      AXorB = x ^ y;
12.      System.out.println("false XOR true: "+AXorB);
13. // Third Case    
14.      A = true;
15.      B = false;
16.      AXorB = x ^ y;
17.      System.out.println("true XOR false: "+AXorB);
18. // Fouth Case
19.      A = true;
20.      B = true;
21.      AXorB = x ^ y;
22.      System.out.println("true XOR true: "+AXorB);
23.   }
24. }

 

The output will be the following:

false XOR false: false
false XOR true: true
true XOR false: true
true XOR true: false

 

Following are the two prominent ways you can use the Java XOR operator:

· Using Java XOR operator instead of AND (&&) or OR (||) operators

Consider a scenario where a Vehicle class has two Boolean attributes: automatic and manual. You want to set the condition that the car can be automatic or manual, but not both.

It can also be executed using other bitwise operators such as AND (&&) and OR (||).

 

The code below shows how it can be done using them:

01. Vehicle myCar = Vehicle.automaticAndManual();
02. boolean automaticXorManual = (myCar.isAutomatic() && !myCar.isManual()) || (!myCar.isautomatic() && myCar.isManual());

Using AND (&&) and OR (||) operators result in a bit longer statement that is quite confusing and can be prone to errors, especially considering that there is a relatively simpler alternative , the Java XOR operator.

 

So, instead of a cumbersome implementation using AND (&&) and OR (||), we can directly use the XOR (^) operator:

01. Vehicle myCar = vehicle.automaticAndManual();
02. boolean automaticXorManual = myCar.isAutomatic() ^ myCar.isManual();

As observed in this code, the XOR operator allows us to be more concise in expressing such conditions where both conditions cannot be the same simultaneously.

 

· Using Java XOR operator for bitwise operations

Being a bitwise operator, XOR can also manipulate each bit in a primitive type. For instance, two integers 3 and 4, whose binary representations will be 00000011 and 000000100 (in 8-bit binary) respectively and using the XOR operator (^) between them will result in the integer 7, 00000111 in an 8-bit binary.

The Initial 3 bits from the right are different in these two numbers; therefore, the result of the XOR operator all first 3 bits from the right will be 1; thus, their bitwise XOR result turns out to be 7.

 

See this code below demonstration this example using the XOR operator for the bitwise operation:

01. public class Xor_example     
02. {     
03.    public static void main(String[] args)     
04.    {     
05.     int num1 = 3, num2 = 4;   //declaring values  
06. // bitwise XOR     
07. // 00000011 ^ 00000100 = 00000111 = 7       
08.     System.out.println("num1 XOR num2 = " + (num1 ^ num2));     
09.    }    
10. }

 

Output:

num1 XOR num2 = 7

Example: Java XOR operator

We discussed the basic operations of the Java XOR operator. There can be several problems where XOR can be utilized. Here is one such problem.

 

· Find the unique value in an array

Suppose you have an array of integers, and you have to find a unique integer. It can be done by traversing the array, storing the frequency of each integer and returning the integer(s) that occurs just once. Still, using the XOR operator will be more efficient as it can be done without a loop.

Consider the input array is [5, 6, 5, 14, 7, 6, 14]. To keep it simple, all the elements in the array occur multiple times except the fifth element, 7. The XOR of all elements can be implemented like this,

5 ^ 6 ^ 5 ^ 14 ^ 7 ^ 6 ^ 14.

It can be written as,

(5 ^ 5) ^ (6 ^ 6) ^ (14 ^ 14) ^ 7

Which will be evaluated in to

0 ^ 0 ^ 0 ^ 7,

And finally, 7 will be returned.

01. public class XOR_example_2
02. {
03.   public static int findUniqueInteger(int[] numArray)
04.     {
05.        int result = numArray [0];
06.        for(int i = 1; i < numArray.length; i++)
07.        result = result ^ numArray[i];
08.        return result;
09.     }
10.   public static void main(String[] args)
11.     {
12.        nt[] myArray = {5, 6, 5, 14, 7, 6, 14};
13.        int uniqueNumber = findUniqueInteger(myArray);
14.        System.out.print("The unique integer in the array is : " + uniqueNumber);
15.     }
16.}

 

Output:

The unique integer in the array is : 7

It is just one of many ways to implement the Java XOR operator in your code. There are be various problems that would be way lengthier and more complicated without using the XOR gate.

See Also: Optional Parameters In Java – Common Strategies and Approaches

 

Conclusion

We have discussed all the basics of the Java XOR operator. Alongside offering a concise way to implement certain conditions, it can also manipulate individual bits in two values. There are various situations where the XOR operator gets it done far more efficiently. With this information, you can quickly implement the Java XOR operator as needed in your code.

new Java jobs

Author

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.

Write A Comment