I want to add a null check to my ternary operator which checks on a Boolean isValue
:
public String getValue() {
return isValue ? "T" : "F";
}
My task is:
What if the Boolean(object) return null? Add a boolean check and return "" (empty String in case if its null).
Note that isValue
is a Boolean
, not boolean
.
A terniary operator has the following syntax:
result = expression ? trueValue : falseValue;
Where trueValue
is returned when the expression evaluates to true
and falseValue
when it doesn't.
If you want to add a null check such that when a Boolean
isValue
is null
then the method returns ""
, it isn't very readable with a terniary operator:
String getValue() {
return isValue == null ? "" : (isValue ? "T" : "F");
}
A statement like that could be better expressed with if
statements. The body of the method would become
final String result;
if (isValue == null) {
result = "";
} else if (isValue) {
result = "T";
} else {
result = "F";
}
return result;