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.

Related Posts

  • Question mark in java
    20 May

    Question mark operator in java

    Learn about Question mark operator in java. It is also know as ternary operator.

  • 27 December

    what does += mean in java

    Learn about += operation in java. It is also known as compound addition assignment operator.

  • 29 March

    Modulo operator in java

    Table of ContentsModulo operator SyntaxModulo operator usagesEven odd programPrime number programModulo operator behaviour with negative integer In this post, we will see about modulo or modulus operator in java. Modulo operator(%) is used to find the remainder when one integer is divided by another integer. Modulo operator Syntax [crayon-60f665e5ebf65147571931/] We can’t use modulo with any […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.