Best method to check if a value of a String is null in Java
Solution 1
Just use a simple ==
. There's no need to overcomplicate this.
Solution 2
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.
Solution 3
-
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 checkmyString
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.
Related videos on Youtube
alona
Updated on June 04, 2022Comments
-
alona almost 2 years
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!
-
alona about 6 yearssorry if my question was not clear, but I was having NPE when comparing it when myString is null, I have updated my question. Thanks! i guess == is not fail safe
-
C.Champagne about 6 years@djrumix123
==
IS fail safe in this case because you don't access any member of a potentially null string.string1.equals(string2)
is not: It will throw a NPE ifstring1
is null. The problem with==
is that it compares references, so it is valid to determine if a string is null or not but it is not pertinent to compare if two string have the same value. -
Mureinik about 6 years@djrumix123 as C.Champagne said - checking
myString != null
is the safest approach, and probably the best performing one too (you're just checking the reference's identity). -
Youcef Laidani about 6 years@djrumix123 the new features also can help you a lot ;)
-
alona about 6 yearsi'll try this though!
-
Hoppeduppeanut about 5 yearsThis will not compile, as
results
is uninitialized. Even if it worked,results==null
would cover the OP's requirements, which have already been covered in previous answers.