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?
10 Answers
StringUtils.isEmpty(str)orStringUtils.isNotEmpty(str)StringUtils.isBlank(str)orStringUtils.isNotBlank(str)
from Apache commons-lang.
The difference between empty and blank is : a string consisted of whitespaces only is blank but isn't empty.
I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.
3If 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.
2com.google.common.base.Strings.isNullOrEmpty(String string) from Google Guava
No, which is why so many other libraries have their own copy :)
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;
} 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 2 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.
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; } 4 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.
1For 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.
5