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...
}

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.


The last and the best one. ie 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


  • 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 (ie, 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.
  • 链接地址: http://www.djcxy.com/p/76202.html

    上一篇: 是否有一个基本的Java Set实现不允许空值?

    下一篇: 在Java中检查空值的最佳方法是什么?