Javatpoint Logo
Javatpoint Logo

XOR and XNOR operators in Java

One of the Bitwise operators offered by Java is XOR. Two boolean operands are given to the XOR (also known as exclusive OR), which returns true if they are different. When neither of the two boolean conditions supplied can be true simultaneously, the XOR operator is most useful.

XOR Operator in Java (Exclusive OR)

The carrot ( ) symbol denotes the XOR operator. If two values are provided, it returns true when they differ; else, it returns false. True gets represented by 1 in binary, whereas false gets represented by 0.

The XOR operator's truth table is shown below:

XOR and XNOR operators in Java

As we can see from the above table, it only returns true if the values of both operands differ. Otherwise, false is returned.

Let's use an illustration to clarify it:

A good XOR operator example

Consider the illustration below:

XorExpl1.java

Output:

XOR and XNOR operators in Java

XNOR operator

The opposite of the binary equivalent of XOR is given by XNOR.

Truth table:

XOR and XNOR operators in Java

If the bits are the same, it returns 1, else it returns 0.

Examples:

Input: 10 20

Output : 1

A Binary of 20 is 10100

A Binary of 10 is 1010

So the XNOR is 00001

So the output is 1

Input : 10 10

Output : 15

A Binary of 10 is 1010

A Binary of 10 is 1010

So the XNOR is 1111

So the output is 15

Method 1:- (O(logn))

In this solution, each bit is checked separately. If two bits match, we output 1; otherwise, we output 0.

Let's explain it using the following code.

XNORExpl1.java

Output:

XOR and XNOR operators in Java

Second Method:- O(1)

  1. Determine the maximum of the two provided numbers.
  2. Flip the highest two numbers' bits.
  3. Return the XOR of the bigger original number and the smaller changed number.

XNORExpl2.java

Output:

XOR and XNOR operators in Java

Third Method: Using XOR

Simply said, A XOR B is the opposite of XNOR of A and B. A bit mask must be created in order to only retrieve the real bits from an inverted binary number because directly inverting any binary number also flips the leading zeroes.

Below is an example of this implementation:

XNORExpl3.java

Output:

XOR and XNOR operators in Java

Time Complexity: O(1)

Auxiliary Space: O(1)


Next TopicAWS Lambda in Java





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