Best way to check for null values in Java?

Solution 1:

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.

Solution 2:

The last and the best one. i.e LOGICAL AND

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

Because in logical &&

it is not necessary to know what the right hand side is, the result must be false

Prefer to read :Java logical operator short-circuiting

Solution 3:

  • Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
  • Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

Solution 4:

Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.

Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.

Method 2 is just making it more complicated than it needs to be.

Method 1 is just method 4 with an extra line of code.