lea*_*ock 0 java ternary-operator wrapper null-check
I want to add a null check to my ternary operator which checks on a Boolean isValue:
public String getValue() {
return isValue ? "T" : "F";
}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |