Javatpoint Logo
Javatpoint Logo

Java XOR

Java XOR is one of the Bitwise operators available in Java. The XOR ( aka exclusive OR) takes two boolean operands and returns true if they are different. The best use case of the XOR operator is when both the given boolean conditions can't be true simultaneously.

Let's understand what the bitwise operators are in Java?

Bitwise Operators in Java

An operator is a symbol that is defined to perform a specific operation. For example, operator '+' is used to add two values. Just like traditional operators, Java provides supports for bitwise operators. These operators are used to perform operations on individual bits of a number. That is why these operators are called bitwise operators. It is evaluated from left to right.

The bitwise operators can be used with any of the integral data types such as int, char, short, etc. Usually, the bitwise operators are used while performing manipulation or query operations over the binary indexed tree.

There are seven types of the bitwise operator in Java that are used to perform bit-level operations:

Operator Description
| Bitwise OR
& Bitwise AND
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Signed Right Shift
>>> Unsigned Right Shift

In this section, we will discuss the Bitwise XOR operator in Java. See all Bitwise Operator in Java.

Java XOR Operator (Exclusive OR)

The XOR operator is denoted by a carrot (^) symbol. It takes two values and returns true if they are different; otherwise returns false. In binary, the true is represented by 1 and false is represented by 0.

Below is the truth table of the XOR operator:

x y x^y
0 0 0
0 1 1
1 0 1
1 1 0

From the above table, we can see it returns true if and only if both operand's values are different. Otherwise, it returns false.

Let's understand it with an example:

Example of XOR operator

Consider the below example:

TestXor.java:

Output:

x ^ y = 2

In the above example, we have defined two values and perform the XOR operation on them. Also, we have added two XOR operations using a traditional operator +. So, we can write the traditional operators to operate two XORs.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA