How to check a string against null in java?
Asked Answered
T

20

103

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

stringname.equalsignorecase(null)

but it's not working.

Tantivy answered 27/5, 2010 at 11:11 Comment(1)
1. equalsignorecase - returns false if the passed argument is null 2. as stringname is a string object you can simply use stringname == nullSeadon
L
181

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.

Laminitis answered 27/5, 2010 at 14:21 Comment(3)
you missed the Yoda version, also works every time: if ("foo".equalsIgnoreCase(string))Deception
Nice helpful explanation. Thanks for playing nice.Aruba
@aioobe I think we agree? If you can be more clear, glad to edit.Laminitis
Z
33
s == null

won't work?

Zosema answered 27/5, 2010 at 11:12 Comment(1)
@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 ==.Gastropod
S
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;
}

;)

Spermatid answered 27/5, 2010 at 11:16 Comment(1)
If you're read this far, please realize that @Spermatid is joking; you shouldn't be doing it this way.Laminitis
L
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;
    }
Lycaonia answered 13/11, 2014 at 10:43 Comment(0)
D
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.

Demount answered 27/5, 2010 at 11:26 Comment(0)
S
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.

Scopula answered 3/12, 2012 at 17:0 Comment(1)
beware of NullPointer in this case the second condition should be first .Downbeat
C
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.

Chemoreceptor answered 27/5, 2010 at 11:19 Comment(0)
M
2

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

if(null == stringName){

  [code]

}

else

[Error Msg]
Misconduct answered 18/2, 2013 at 5:24 Comment(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.Hughey
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 possibleCollings
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.Frameup
U
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)); 
Unspotted answered 18/3, 2016 at 6:54 Comment(0)
P
2

You can check with String == null

This works for me

    String foo = null;
    if(foo == null){
        System.out.println("String is null");
    }
Plumage answered 19/8, 2016 at 8:38 Comment(0)
U
2

Simple method:

public static boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
Unholy answered 1/11, 2016 at 19:31 Comment(0)
B
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

Blame answered 31/1, 2014 at 8:37 Comment(0)
O
1

With Java 7 you can use

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

which will return true if both parameters are null.

Ornelas answered 24/4, 2019 at 9:45 Comment(0)
D
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
Duky answered 25/7, 2020 at 19:10 Comment(0)
P
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.

Pittman answered 26/11, 2013 at 14:52 Comment(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?Axolotl
M
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.

Menis answered 26/1, 2017 at 9:27 Comment(2)
Using Scala (with Java) if(value.isEmpty()) gives NullPointerException. In this case is better using if(value == null)Albric
This is definitely wrong as it will always throw NPE if null.Woman
S
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.

Sungod answered 29/4, 2021 at 11:22 Comment(0)
S
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.

Simonsimona answered 14/2, 2024 at 12:40 Comment(0)
F
-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.

Flippant answered 27/5, 2010 at 14:12 Comment(4)
It doesn't - so this is not a fix and not a useful answer.Lancinate
I would like to be the first to say: "wat"Axolotl
this does not answer the questionEndow
This should be the wrong answer, surely, but it's not. Unbelievable. The only answer here that actually works in Android.Metonymy
P
-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..

Parkway answered 7/2, 2014 at 15:21 Comment(1)
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.Lancinate

© 2022 - 2025 — McMap. All rights reserved.