Arty-fishL Arty-fishL - 16 days ago 5
Java Question

Best way to check for null values in Java?

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

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.