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?
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?
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.
!str.equals(null)
will
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.
query != null
better as !query.equals(null)
will throw an exception when query is actually null. Also query != null
is easily readable