Best way to check for null values in Java?

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

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

提交回复
热议问题