Reputation: 33
there are many implementation in how to check whether a String value is null and I'm really confused what to use!
These are my searches so far:
if(myString == null){}
Objects.equals(null, myString);
ObjectUtils.isEmpty(myString)
myString.equals(null)
myString.compareTo(null);
NOTE: This is all about performance, reliable coding, fail-safe and other security purposes!
Updated: myString is dynamic, what if it was null, some of the implementation above will throw NullPointerException!
Upvotes: 1
Views: 18104
Reputation: 28279
if(myString == null)
Easiest and right way.
Objects.equals(null, myString)
A right way, its implemention is based on 1.
ObjectUtils.isEmpty(myString)
Not sure which ObjectUtils
you are working with, but it seems to check myString
is empty, not null.
myString.equals(null)
This does not work when myString
is null, NPE will be thrown.
myString.compareTo(null)
This does not work when myString
is null, NPE will be thrown.
Upvotes: 5
Reputation: 59960
Another Option if you are using Java 8 you can use Optional::ofNullable
Optional.ofNullable(myString).isPresent()// true if not null, false if null
You can even use :
Optional.ofNullable(myString)
.orElseThrow(() -> new Exception("If null throw an exception"));
There are many Options, just read the documentation
But as Mureinik mention in his answer ==
is enough in your case.
Upvotes: 8