Edward
Edward

Reputation: 4631

How to turn null into false in Java?

In my code I have a org.apache.tapestry5.json.JSONObject named j. I want to read the property use-name from that Object:

Boolean isUseName       = (Boolean) j.opt("use-name");

The value can either be true, false or null (if the entry is not present in the JSONObject). Now I'd like to use isUseName for a conditional statement:

if(!isUseName) {System.out.println("No Name to be used.")}

This gives me a NullPointerException if "use-name" was not in the JSONObject. One way is to simply check first if isUseName is null, e.g.

if(isUseName != null && !isUseName) {System.out.println("No Name to be used.")}

I was wondering, if there is a more elegant way. Is it e.g. possible to (automatically) set isUseName to false, if j.opt() returns null? One thing that came to my mind is using a ternary expression, but this has a redundant j.opt("use-name"):

Boolean isUseName = (j.opt("use-name") != null)
                  ? (Boolean) j.opt("use-name")
                  : false;

Upvotes: 2

Views: 325

Answers (3)

stealthjong
stealthjong

Reputation: 11093

How about check if the key exists

boolean useName = j.has("use-name") ? j.getBoolean("use-name") : false;

Upvotes: 0

Svante
Svante

Reputation: 51501

You could compare with Boolean.TRUE:

boolean useName = Boolean.TRUE.equals (j.opt ("use-name"));

Upvotes: 12

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Logical expressions short-circuit, so if you check null first, then you can use it after the check:

if(isUseName != null && !isUseName) {
    // It's not null, and false
    System.out.println("No Name to be used.");
}

or

if(isUseName == null || !isUseName) {
    // It's null or false
    System.out.println("No Name to be used.");
}

and similarly

if(isUseName != null && isUseName) {
    // It's not null, and true
}

and

if(isUseName == null || isUseName) {
    // It's either null or true
}

Upvotes: 0

Related Questions