[java] How to check a string against null in java?

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

stringname.equalsignorecase(null)

but it's not working.

This question is related to java string null

The answer is


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.


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

With Java 7 you can use

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

which will return true if both parameters are null.


Simple method:

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

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.


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


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

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.


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

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.


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

if(null == stringName){

  [code]

}

else

[Error Msg]

s == null

won't work?


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.


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.


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


You can check with String == null

This works for me

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

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.


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

;)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"