Best way to check for null values in Java?
- by Arty-fishL
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...
}