Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 483
yonikawa Avatar asked Nov 26 '22 23:11

yonikawa


1 Answers

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.

like image 53
Rohit Jain Avatar answered Jan 26 '23 16:01

Rohit Jain