i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.
1) Below does not account for all spaces like in case of empty XML tag
return inputString==null || inputString.length()==0;
2) Below one takes care but trim can eat some performance + memory
return inputString==null || inputString.trim().length()==0;
3) Combining one and two can save some performance + memory (As Chris suggested in comments)
return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;
4) Converted to pattern matcher (invoked only when string is non zero length)
private static final Pattern p = Pattern.compile("\\s+");
return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();
5) Using libraries like -
Apache Commons (StringUtils.isBlank/isEmpty
)
or Spring (StringUtils.isEmpty
)
or Guava (Strings.isNullOrEmpty
)
or any other option?
OR
TextUtils.isNotBlank(label);
the last solution will check if not null and trimm the str at the same time
If you have to test more than one string in the same validation, you can do something like this:
So, you can use this like
StringHelper.hasBlank("Hello", null, "", " ")
orStringHelper.hasBlank("Hello")
in a generic form.To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:
or if blank spaces need to be detected as well:
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
Simply and clearly:
Apache Commons Lang has
StringUtils.isEmpty(String str)
method which returns true if argument is empty or nullUseful method from Apache Commons:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)