Best way to check for null values in Java?

后端 未结 16 1092
傲寒
傲寒 2020-12-04 16:30

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 abou

相关标签:
16条回答
  • 2020-12-04 17:12

    We can use Object.requireNonNull static method of Object class. Implementation is below

    public void someMethod(SomeClass obj) {
        Objects.requireNonNull(obj, "Validation error, obj cannot be null");
    }
    
    0 讨论(0)
  • 2020-12-04 17:13

    As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.

    // You meant to do this
    if(foo != null){
    
    // But you made a typo like this which will always evaluate to true
    if(foo = null)
    
    // Do the comparison in this way
    if(null != foo)
    
    // So if you make the mistake in this way the compiler will catch it
    if(null = foo){
    
    // obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
    if(foo == null){
    if(foo =  null){
    
    0 讨论(0)
  • 2020-12-04 17:14

    If at all you going to check with double equal "==" then check null with object ref like

    if(null == obj) 
    

    instead of

    if(obj == null)
    

    because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).

    0 讨论(0)
  • 2020-12-04 17:15

    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

    0 讨论(0)
  • 2020-12-04 17:15
    • 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.
    0 讨论(0)
  • 2020-12-04 17:16

    I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.

    That doesn't always feel right to me.

    0 讨论(0)
提交回复
热议问题