XOR operator in java

In this tutorial, we will see about XOR operator in java.

XOR operator or exclusive OR takes two boolean operands and returns true if two boolean operands are different.

XOR operator can be used when both the boolean conditions can’t be true simultaneously.

Here is truth table for XOR operator.

PQP XOR Q
truetruefalse
truefalsetrue
falsetruetrue
falsefalsefalse


Let’s say you have Person class and you want to filter persons who is either Male or Adult but not both from list of persons.

Create Main classed named PersonXORMain.java

Output:

[Name:Martin Age:17 Gender:Male, Name:Amy Age:25 Gender:Female]

As you can see we are able to achieve the condition with help of && and || operators but if statement looks quite verbose.

You can use XOR operator to achieve the same.

Replace if((p.isMale() && !p.isAdult()) || (!p.isMale() && p.isAdult())) with if((p.isMale() ^ p.isAdult())) and you should be able to achieve same results.

BitWise XOR operator

XOR operator works with primitive type as well. Bitwise XOR operator will always return output as 1 if either of its input 1 but not both.
Here is truth table for BitWise XOR operator.

PQP XOR Q
110
101
011
000

Let’s see this with the help of example.

Output:

XOR of 2 and 3: 1

Let’s understand how XOR of 2 and 3 is 1.
XORBItWise
As you can see, XOR operator returns output as 1 if either of its input 1 but not both.

That’s all about XOR operator in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *