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
?
views:
1041answers:
6StringUtils.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 this.
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;
}
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.
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;
}