Best way to check for null values in Java?

Arty-fishL picture Arty-fishL · Jun 25, 2013 · Viewed 150.8k times · Source

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?

// Method 1
if (foo != null) {
    if (foo.bar()) {
        etc...
    }
}

// Method 2
if (foo != null ? foo.bar() : false) {
    etc...
}

// Method 3
try {
    if (foo.bar()) {
        etc...
    }
} catch (NullPointerException e) {
}

// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
    etc...
}

Answer

Jared Nielsen picture Jared Nielsen · Jun 25, 2013

Method 4 is best.

if(foo != null && foo.bar()) {
   someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.