How to check a string against null in java?

393,968

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.

Share:
393,968

Related videos on Youtube

user351809
Author by

user351809

Updated on April 30, 2021

Comments

  • user351809
    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
      Debu over 2 years
      1. equalsignorecase - returns false if the passed argument is null 2. as stringname is a string object you can simply use stringname == null
  • Felix Kling
    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 is null, you use ==.
  • Dean J
    Dean J about 14 years
    If you're read this far, please realize that @aioobe is joking; you shouldn't be doing it this way.
  • Omry Yadan
    Omry Yadan about 14 years
    you missed the Yoda version, also works every time: if ("foo".equalsIgnoreCase(string))
  • james.garriss
    james.garriss over 11 years
    Nice helpful explanation. Thanks for playing nice.
  • Pawan
    Pawan over 11 years
    beware of NullPointer in this case the second condition should be first .
  • Lukasz 'Severiaan' Grela
    Lukasz 'Severiaan' Grela over 10 years
    why 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
    Sarajog over 10 years
    normally 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
    RichieHH about 10 years
    It'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
    Chris Stratton almost 10 years
    No! .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
    Chris Stratton almost 10 years
    It doesn't - so this is not a fix and not a useful answer.
  • philo vivero
    philo vivero over 9 years
    What 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
    philo vivero over 9 years
    I would like to be the first to say: "wat"
  • Dean J
    Dean J about 9 years
    @aioobe I think we agree? If you can be more clear, glad to edit.
  • jason adams
    jason adams about 8 years
    this does not answer the question
  • Andrea
    Andrea almost 7 years
    Using Scala (with Java) if(value.isEmpty()) gives NullPointerException. In this case is better using if(value == null)
  • Roger
    Roger over 6 years
    This is definitely wrong as it will always throw NPE if null.