Java string null check by! = Null or! Str.equals (null)?

What is the best way to check non-empty values โ€‹โ€‹in java.

String query ="abcd"; 

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

what's better? why?

+4
source share
4 answers

Option 1 is better (and parameter only ), because option 2 will throw NPE when your value is really null . So simple.

Try the following:

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

So, basically the test that you wanted to run on your own NullPointerException in the second case. So this is not a choice.

+24
source

!str.equals(null) will be

  • always returns false if it does not throw an exception, and
  • throws an exception if str is null

The point of null checking is to make sure that the link in this str code actually refers to the object. If this value is null, you cannot invoke any methods on it, including equals , without throwing a NullPointerException ... that the null checkpoint should avoid.

So !str.equals(null) leads to the fact that the very problems with null checks are designed to prevent and do not do what you think at all. Never do that.

+11
source

query != null better because !query.equals(null) will throw an exception when the query is actually null. Also query != null easy to read

+2
source

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

+2
source

All Articles