103

How can I check a string against null in java? I am using

stringname.equalsignorecase(null)

but it's not working.

1
  • 1. equalsignorecase - returns false if the passed argument is null 2. as stringname is a string object you can simply use stringname == null
    – Debu
    Commented Jan 17, 2022 at 8:04

20 Answers 20

182

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.

3
  • 2
    you missed the Yoda version, also works every time: if ("foo".equalsIgnoreCase(string))
    – Omry Yadan
    Commented May 27, 2010 at 14:26
  • 2
    Nice helpful explanation. Thanks for playing nice. Commented Sep 12, 2012 at 13:48
  • @aioobe I think we agree? If you can be more clear, glad to edit.
    – Dean J
    Commented Apr 10, 2015 at 3:02
33
s == null

won't work?

1
  • 4
    @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 ==. Commented May 27, 2010 at 11:16
17

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;
}

;)

1
  • 31
    If you're read this far, please realize that @aioobe is joking; you shouldn't be doing it this way.
    – Dean J
    Commented May 27, 2010 at 14:14
12

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;
    }
6

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.

4

This looks a bit strange, but...

stringName == null || "".equals(stringName)

Never had any issues doing it this way, plus it's a safer way to check while avoiding potential null point exceptions.

1
  • beware of NullPointer in this case the second condition should be first .
    – Pawan
    Commented Feb 3, 2013 at 4:54
3

I'm not sure what was wrong with The MYYN's answer.

if (yourString != null) {
  //do fun stuff with yourString here
}

The above null check is quite alright.

If you are trying to check if a String reference is equal (ignoring case) to another string that you know is not a null reference, then do something like this:

String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
  //do fun stuff
}

If there is any doubt as to whether or not you have null references for both Strings you are comparing, you'll need to check for a null reference on at least one of them to avoid the possibility of a NullPointerException.

2

If your string having "null" value then you can use

if(null == stringName){

  [code]

}

else

[Error Msg]
3
  • 3
    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. Commented Sep 13, 2013 at 8:39
  • 8
    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
    – Sarajog
    Commented Sep 20, 2013 at 12:39
  • 4
    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.
    – RichieHH
    Commented Mar 5, 2014 at 11:52
2

import it in your class

import org.apache.commons.lang.StringUtils;

then use it, they both will return true

System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(null)); 
2

You can check with String == null

This works for me

    String foo = null;
    if(foo == null){
        System.out.println("String is null");
    }
2

Simple method:

public static boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
0
1

Of course user351809, stringname.equalsignorecase(null) will throw NullPointerException.
See, you have a string object stringname, which follows 2 possible conditions:-

  1. stringname has a some non-null string value (say "computer"):
    Your code will work fine as it takes the form
    "computer".equalsignorecase(null)
    and you get the expected response as false.
  2. stringname has a null value:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, null is not an object that can execute the equalsignorecase() method.

Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null

1

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

1

If I understand correctly, this should do it:

if(!stringname.isEmpty())
// an if to check if stringname is not null
if(stringname.isEmpty())
// an if to check if stringname is null
0

I realize this was answered a long time ago, but I haven't seen this posted, so I thought I'd share what I do. This isn't particularly good for code readability, but if you're having to do a series of null checks, I like to use:

String someString = someObject.getProperty() == null ? "" : someObject.getProperty().trim();

In this example, trim is called on the string, which would throw an NPE if the string was null or spaces, but on the same line, you can check for null or blank so you don't end up with a ton of (more) difficult to format if blocks.

1
  • 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? Commented Dec 31, 2014 at 16:37
0

If the value returned is null, use:

if(value.isEmpty());

Sometime to check null, if(value == null) in java, it might not give true even the String is null.

2
  • 1
    Using Scala (with Java) if(value.isEmpty()) gives NullPointerException. In this case is better using if(value == null)
    – Andrea
    Commented Jun 6, 2017 at 15:07
  • 1
    This is definitely wrong as it will always throw NPE if null.
    – Roger
    Commented Jan 5, 2018 at 21:11
0

The Apache StringUtils class will do this for you. StringUtils.equals(col1, col2) works correctly when col1, col2, or both are null.

Consider reading the entire StringUtils JavaDoc page. It has solved most if not all of the String manipulation and/or comparison problems you will encounter.

0

If you use equalsIgnoreCase for a null String, it will throw NullPointerException.

Therefore, you can use this:

    String one = null;
    String other = "ntg";
    try {
        one.equalsIgnoreCase(other);
    } catch (NullPointerException e) {
        System.out.println("The first string is null.");
    }

but I recommend using String == null.

-1

Well, the last time someone asked this silly question, the answer was:

someString.equals("null")

This "fix" only hides the bigger problem of how null becomes "null" in the first place, though.

4
  • It doesn't - so this is not a fix and not a useful answer. Commented Jun 5, 2014 at 15:57
  • I would like to be the first to say: "wat" Commented Dec 31, 2014 at 16:39
  • this does not answer the question Commented May 14, 2016 at 2:37
  • This should be the wrong answer, surely, but it's not. Unbelievable. The only answer here that actually works in Android.
    – arcady bob
    Commented Apr 27, 2023 at 0:48
-3

There are two ways to do it..Say String==null or string.equals()..

public class IfElse {

    public int ifElseTesting(String a){
        //return null;
        return (a== null)? 0: a.length();
    }

}

public class ShortCutifElseTesting {

    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        System.out.println("enter the string please:");
        String a=scanner.nextLine();
        /*
        if (a.equals(null)){
            System.out.println("you are not correct");
        }
        else if(a.equals("bangladesh")){
            System.out.println("you are right");
        }
        else
            System.out.println("succesful tested");

        */
        IfElse ie=new IfElse();
        int result=ie.ifElseTesting(a);
        System.out.println(result);

    }

}

Check this example..Here is an another example of shortcut version of If Else..

1
  • 2
    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. Commented Jun 5, 2014 at 15:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.