How to check a string against null in java?
Solution 1
string == null
compares if the object is null. string.equals("foo")
compares the value inside of that object. string == "foo"
doesn't always work, because you're trying to see if the objects are the same, not the values they represent.
Longer answer:
If you try this, it won't work, as you've found:
String foo = null;
if (foo.equals(null)) {
// That fails every time.
}
The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.
What you probably wanted was:
String foo = null;
if (foo == null) {
// That will work.
}
The typical way to guard yourself against a null when dealing with Strings is:
String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
// Do something here.
}
That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.
The easy way, if you're using a String literal (instead of a variable), is:
String foo = null;
...
if ("some String".equals(foo)) {
// Do something here.
}
If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.
if (StringUtils.equals(foo, bar)) {
// Do something here.
}
Another response was joking, and said you should do this:
boolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.
In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.
Solution 2
s == null
won't work?
Solution 3
Sure it works. You're missing out a vital part of the code. You just need to do like this:
boolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
;)
Solution 4
Use TextUtils Method if u working in Android.
TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length
if(TextUtils.isEmpty(str)) {
// str is null or lenght is 0
}
Below is source code of this method.You can use direclty.
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* @return true if str is null or zero length
*/
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
Solution 5
If we look at the implementation of the equalsIgnoreCase method, we find this part:
if (string == null || count != string.count) {
return false;
}
So it will always return false
if the argument is null
. And this is obviously right, because the only case where it should return true
is when equalsIgnoreCase was invoked on a null String
, but
String nullString = null;
nullString.equalsIgnoreCase(null);
will definitely result in a NullPointerException.
So equals methods are not designed to test whether an object is null, just because you can't invoke them on null
.
Related videos on Youtube
user351809
Updated on April 30, 2021Comments
-
user351809 about 3 years
How can I check a string against null in java? I am using
stringname.equalsignorecase(null)
but it's not working.
-
Debu over 2 years1. equalsignorecase - returns false if the passed argument is null 2. as stringname is a string object you can simply use stringname == null
-
-
Felix Kling about 14 years@k38: You "only" have to use
equals()
if you want to compare values. But if you want to check whether a variable isnull
, you use==
. -
Dean J about 14 yearsIf you're read this far, please realize that @aioobe is joking; you shouldn't be doing it this way.
-
Omry Yadan about 14 yearsyou missed the Yoda version, also works every time: if ("foo".equalsIgnoreCase(string))
-
james.garriss over 11 yearsNice helpful explanation. Thanks for playing nice.
-
Pawan over 11 yearsbeware of NullPointer in this case the second condition should be first .
-
Lukasz 'Severiaan' Grela over 10 yearswhy null == stringName and not stringName == null ? I assume that there is no difference but why this is preferred (and I've seen it a lot). My preference is reading order LTR so stringName == null but want to know what other people thinks.
-
Sarajog over 10 yearsnormally in comparison you put the variable on the right side, so that you won't initialize the variable on mistake: null = stringName produces a compile Error while stringName = null would be possible
-
RichieHH about 10 yearsIt's not "normal" to do this at all and many people expressly forbid it since its not naturally readable to someone reading the code base.
-
Chris Stratton almost 10 yearsNo! .equals() must not be used with a potentially null object, so the introductory explanation is mistaken. And the rest of this answer seems pointless and unrelated to the question asked.
-
Chris Stratton almost 10 yearsIt doesn't - so this is not a fix and not a useful answer.
-
philo vivero over 9 yearsWhat do you mean checking for null or blank? You're only checking for null here. The blank is one of the possible returns of the "COND ? A : B;" construct, right?
-
philo vivero over 9 yearsI would like to be the first to say: "wat"
-
Dean J about 9 years@aioobe I think we agree? If you can be more clear, glad to edit.
-
jason adams about 8 yearsthis does not answer the question
-
Andrea almost 7 yearsUsing Scala (with Java)
if(value.isEmpty())
givesNullPointerException
. In this case is better usingif(value == null)
-
Roger over 6 yearsThis is definitely wrong as it will always throw NPE if null.