This post is older than a year. Consider some information might not be accurate anymore.
This operator (?) is also known as the ternary operator because it uses three operands. Instead of an if-then-else statement this operator can make your code more readable, when something is so simple you don’t want to waste many lines for.
I have stumbled recently over this code in a stackoverflow post:
String str = "Y";//or else "N"
boolean isManager = (str.equals("Y")) ? true : false;
Critical points from my point of view:
- parenthesis is unnecessary
- a control flow issue, since
str.equals("Y")
already returnstrue
orfalse
, the use of the ternary operator is redundant
Clean code
String str = "Y";//or else "N"
boolean isManager = str.equals("Y");