Best way to verify string is empty or null

prash picture prash · Sep 14, 2015 · Viewed 100.5k times · Source

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?

Answer

puczo picture puczo · Sep 14, 2015

Useful method from Apache Commons:

 org.apache.commons.lang.StringUtils.isBlank(String str)

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)