0

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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
learn n rock
  • 59
  • 1
  • 5
  • 2
    is `isValue` a primitive boolean? If it is, then it will never be null. Also, ternary is `a ? b : c` – Compass Aug 12 '19 at 20:07
  • To expand on what @Compass said, primitive types cannot be null, only Objects such as `Boolean` or `String`, not `int` or `boolean`. Primitive types have inherit default values, for example `int` defaults to `0`. – Nexevis Aug 12 '19 at 20:09
  • @Nexevis it is an Object (Boolean) – learn n rock Aug 12 '19 at 20:12
  • @learn n rock I recommend you edit your question with that information then, you specifically use the term `boolean` which implies the primitive type. – Nexevis Aug 12 '19 at 20:12
  • Thank You @Nexevis my mistake – learn n rock Aug 12 '19 at 20:13

3 Answers3

7

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;
geco17
  • 5,152
  • 3
  • 21
  • 38
3

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.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
2

You could do

return Optional.ofNullable(isValue).map(t -> t ? "T": "F").orElse("");
Reimeus
  • 158,255
  • 15
  • 216
  • 276