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

Peter picture Peter · Oct 2, 2008 · Viewed 137.8k times · Source

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.

Answer

Mike F picture Mike F · Oct 2, 2008

You can simply use != instead.