[java] Is it good practice to use the xor operator for boolean checks?

I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write

if (boolean1 ^ boolean2)
{
  //do it
}

than

if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.

I'm curious as to the best practices regarding the usage of the ^ operator.

The answer is


if((boolean1 && !boolean2) || (boolean2 && !boolean1)) 
{ 
  //do it 
} 

IMHO this code could be simplified:

if(boolean1 != boolean2) 
{ 
  //do it 
} 

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.


I recently used an xor in a JavaScript project at work and ended up adding 7 lines of comments to explain what was going on. The justification for using xor in that context was that one of the terms (term1 in the example below) could take on not two but three values: undefined, true or false while the other (term2) could be true or false. I would have had to add an additional check for the undefined cases but with xor, the following was sufficient since the xor forces the first term to be first evaluated as a Boolean, letting undefined get treated as false:

if (term1 ^ term2) { ...

It was, in the end, a bit of an overkill, but I wanted to keep it in there anyway, as sort of an easter egg.


You could always just wrap it in a function to give it a verbose name:

public static boolean XOR(boolean A, boolean B) {
    return A ^ B;
}

But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.

You can also use XOR to swap the values in two variables without using a third temporary variable.

// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;

Here's a Stackoverflow question related to XOR swapping.


str.contains("!=") ^ str.startsWith("not(")

looks better for me than

str.contains("!=") != str.startsWith("not(")

With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:

flags = flags ^ MASK;

This article by Vipan Singla explains the usage case more in detail.

If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.


I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.

My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.

As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.


I think it'd be okay if you commented it, e.g. // ^ == XOR.


I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.

If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.


I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.

If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".

For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:

if (isDifferent(boolean1, boolean2))
{
  //do it
}

Your "isDifferent(boolean1, boolean2)" function would look like:

private boolean isDifferent(boolean1, boolean2)
{
    return boolean1 ^ boolean2;
}

Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!


If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?

The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.

public static boolean xor(boolean a, boolean b) {
    return (a && !b) || (b && !a);
}

As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.

My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to conditional

Pandas/Python: Set value of one column based on value in another column Run an Ansible task only when the variable contains a specific string (Excel) Conditional Formatting based on Adjacent Cell Value Laravel Checking If a Record Exists Multiple conditions in if statement shell script The condition has length > 1 and only the first element will be used Creating a new column based on if-elif-else condition How to conditional format based on multiple specific text in Excel Using SUMIFS with multiple AND OR conditions Replacing Numpy elements if condition is met

Examples related to bitwise-operators

What is (x & 1) and (x >>= 1)? Convert to binary and keep leading zeros in Python What does AND 0xFF do? What is Bit Masking? Why do we usually use || over |? What is the difference? What does a bitwise shift (left or right) do and what is it used for? What is the difference between & and && in Java? Differences in boolean operators: & vs && and | vs || How does bitshifting work in Java? Getting each individual digit from a whole integer

Examples related to logical-operators

Javascript logical "!==" operator? Java logical operator short-circuiting Boolean operators && and || Simple logical operators in Bash Logical Operators, || or OR? Differences in boolean operators: & vs && and | vs || Python's equivalent of && (logical-and) in an if-statement Logical operators ("and", "or") in DOS batch Logical XOR operator in C++? What's the difference between & and && in MATLAB?

Examples related to xor

bitwise XOR of hex numbers in python T-SQL XOR Operator XOR operation with two strings in java Creating a "logical exclusive or" operator in Java Is it good practice to use the xor operator for boolean checks?