How to avoid null checking in Java?

后端 未结 30 3934
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  没有蜡笔的小新
    2020-11-21 05:40

    Only for this situation -

    Not checking if a variable is null before invoking an equals method (a string compare example below):

    if ( foo.equals("bar") ) {
     // ...
    }
    

    will result in a NullPointerException if foo doesn't exist.

    You can avoid that if you compare your Strings like this:

    if ( "bar".equals(foo) ) {
     // ...
    }
    

提交回复
热议问题