learn n rock
learn n rock

Reputation: 59

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.

Upvotes: 0

Views: 5672

Answers (3)

Reimeus
Reimeus

Reputation: 159754

You could do

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

Upvotes: 2

Nexevis
Nexevis

Reputation: 4667

You are using the incorrect syntax for the ternary operator as pointed out from the comments which should be 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.

Upvotes: 3

geco17
geco17

Reputation: 5294

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;

Upvotes: 7

Related Questions