Best way to check for null values in Java?

Posted by Arty-fishL on Stack Overflow See other posts from Stack Overflow or by Arty-fishL
Published on 2013-06-25T16:08:35Z Indexed on 2013/06/25 16:21 UTC
Read the original article Hit count: 296

Filed under:
|
|

I need to check whether the function of an object returns true or false in Java, but that object may be null, so obviously then the function would throw a NullPointerException. This means I need to check if the object is null before checking the value of the function.

What is the best way to go about this?
I've listed some methods I considered, I just want to know the most sensible one, the one that is best programming practice for Java (opinion?).

// 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 all the time, would it still call foo.bar()?
if (foo != null && foo.bar()) {
    etc...
}

© Stack Overflow or respective owner

Related posts about java

Related posts about null