Best way to check for null values in Java?

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

    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.

提交回复
热议问题