How to check a string against null in java?

JavaStringNull

Java Problem Overview


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

stringname.equalsignorecase(null)

but it's not working.

Java Solutions


Solution 1 - Java

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 - Java

s == null

won't work?

Solution 3 - Java

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 - Java

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 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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

if(null == stringName){

  [code]

}

else

[Error Msg]

Solution 9 - Java

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

Solution 10 - Java

You can check with String == null

This works for me

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

Solution 11 - Java

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

Solution 12 - Java

Simple method:

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

Solution 13 - Java

With Java 7 you can use

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

which will return true if both parameters are null.

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

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.

Solution 17 - Java

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.

Solution 18 - Java

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.

Solution 19 - Java

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..

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser351809View Question on Stackoverflow
Solution 1 - JavaDean JView Answer on Stackoverflow
Solution 2 - JavamikuView Answer on Stackoverflow
Solution 3 - JavaaioobeView Answer on Stackoverflow
Solution 4 - JavaKishan VaghelaView Answer on Stackoverflow
Solution 5 - JavaAndreas DolkView Answer on Stackoverflow
Solution 6 - JavaTimothy PerezView Answer on Stackoverflow
Solution 7 - JavawhaleyView Answer on Stackoverflow
Solution 8 - JavaUser_86View Answer on Stackoverflow
Solution 9 - JavaKhalid HabibView Answer on Stackoverflow
Solution 10 - JavaDon ThomasView Answer on Stackoverflow
Solution 11 - JavaSatyendraView Answer on Stackoverflow
Solution 12 - JavaAlberto CerqueiraView Answer on Stackoverflow
Solution 13 - JavaRoland EttingerView Answer on Stackoverflow
Solution 14 - JavarandomDudeView Answer on Stackoverflow
Solution 15 - JavaReeseView Answer on Stackoverflow
Solution 16 - JavaTripathee GauravView Answer on Stackoverflow
Solution 17 - JavaGuruView Answer on Stackoverflow
Solution 18 - JavapolygenelubricantsView Answer on Stackoverflow
Solution 19 - JavaOmar Faroque AnikView Answer on Stackoverflow