Ternary Operator vs XOR Operator in Java

bitwise-operatorsjavaoperators

I have read in a recent code review that both ternary operator (condition ? foo : bar) and the XOR operator ^ are rarely used in Java. Is it true?

If yes, is this because they are less readable? or some other reason.

Best Answer

The ternary operator is well used, especially for short null-checks / defaults:

System.out.println("foo is "+(foo==null) ? "not set" : foo);

Some people consider this not as readable as an if/else, but that was not the question.

The XOR bitwise operator is only used in bit-processing. If you need a bitwise XOR, then there is no way around it.

The XOR logical operator is indeed so rare, that I did not see it in the last ten year in Java in valid cases. This is also due to the fact, that the boolean XOR "does not scale" like || or &&. What I mean:

if( a && b && c && d ) ....   // it's clear what the intention is
if( a || b || c || d ) ....   // here also
if( a ^  b ^  c ^  d ) ....   // ???

In the last case I would guess, the coder meant "only one should be true". But XOR is a beast. The coder got the beast and not what (s)he wanted.

That would be an interesting interview question: What is the result of the last if?