简体   繁体   中英

How to check Boolean for null?

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;

You are using the incorrect syntax for the ternary operator as pointed out from the comments which should be isValue ? "T" : "F" isValue ? "T" : "F" . I suggest using a solution that mixes the ternary operator with a standard if statement to check for a null value.

Here is what that solution looks like:

public String getValue() {
    if (isValue == null) {
        return "";
    }
    return isValue ? "T" : "F";
}

This will check for null before anything else and return an empty String if the value is null . Otherwise it will check the value as normal and return the String value of T or F for true or false respectively.

你可以做

return Optional.ofNullable(isValue).map(t -> t ? "T": "F").orElse("");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM