Java string null check by != null or !str.equals(null)? [duplicate]

和自甴很熟 提交于 2021-02-07 18:21:59

问题


What's the best way to check for not null values in java.

String query ="abcd";

query != null vs !query.equals(null).

which is better?why?


回答1:


1st one is better (and the only option), because 2nd one will throw NPE, when your value is actually null. As simple as that.

Try this out:

String str = null;
str.equals(null);  // will throw `NPE`.

So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.




回答2:


!str.equals(null) will

  1. always return false if it does not throw an exception, and
  2. throw an exception if str is null

The point of a null check is to make sure the reference, in this code str, actually refers to an object. If it is null, you can't call any methods on it, including equals, without throwing a NullPointerException... which the point of null checks is to avoid happening.

So !str.equals(null) causes the very problem null checks are meant to prevent and doesn't do what you think at all. Never do this.




回答3:


query != null better as !query.equals(null) will throw an exception when query is actually null. Also query != null is easily readable




回答4:


query != null compares if the object is null. query.equals("something") compares the value inside of that object. string == "something". so in this case use query != null.



来源:https://stackoverflow.com/questions/14863055/java-string-null-check-by-null-or-str-equalsnull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!