[java] String isNullOrEmpty in Java?

This surely has been asked before, but Googling doesn't find it. Is there, in any of the standard java libraries (including apache/google/...), a static isNullOrEmpty() method for Strings?

This question is related to java string

The answer is


To check if a string got any characters, ie. not null or whitespaces, check StringUtils.hasText-method (if you are using Spring of course)

Example:

StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true

For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.


In addition to the other answers, I ran across this because I'm a C# programmer primarily, but trying to keep fresh in Java. I noticed that when I tried to use StringUtils my IDE (Eclipse) imported it from com.mysql.jdbc.StringUtils which actually has an isNullOrEmpty(myStringObject) method.

ex.

import com.mysql.jdbc.StringUtils;

StringUtils.isNullOrEmpty(host)

Just another alternative for those who already have the MySQL connector referenced in your project, but not the other StringUtils library.


com.google.common.base.Strings.isNullOrEmpty(String string) from Google Guava


I've seen this method written a few times in projects I've been on but I have to say I've never written it myself, or called it either ... Generally I find null and empty are completely distinct conditions and I have no reason to ever conflate them.


You can add one

public static boolean isNullOrBlank(String param) { 
    return param == null || param.trim().length() == 0;
}

I have

public static boolean isSet(String param) { 
    // doesn't ignore spaces, but does save an object creation.
    return param != null && param.length() != 0; 
}

No, which is why so many other libraries have their own copy :)


If you are doing android development, you can use:

TextUtils.isEmpty (CharSequence str) 

Added in API level 1 Returns true if the string is null or 0-length.


public static boolean isNull(String str) {
        return str == null ? true : false;
    }

    public static boolean isNullOrBlank(String param) {
        if (isNull(param) || param.trim().length() == 0) {
            return true;
        }
        return false;
    }