Best way to check for null values in Java?

后端 未结 16 1194
傲寒
傲寒 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: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

提交回复
热议问题