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.
migrated from stackoverflow.com Mar 11 '12 at 13:15
This question came from our site for professional and enthusiast programmers.
The ternary operator is well used, especially for short null-checks / defaults:
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
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
I used to find the ternary operator difficult to parse, but I've since found that there are some places where it is very useful. These don't tend to be application logic, but logging.
To me, that's a lot neater than either
In summary, it's a question of where it's being used and for that.
As for bit-wise, I still struggle with those but that's because I'm used to working at a high level of abstraction, as other commenters have suggested. If I do come across somewhere in code that someone's decided to use that to be "efficient", the time wasted while I figure it out negates benefits.
This is more of an opinion-based answer but in my case: