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?
isEmpty(String) , which checks if a string is an empty string or null. It also provides the StringUtils. isBlank(String) method, which also checks for whitespace. That's all about determining whether a String is empty or null in Java.
isEmpty(<string>) Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.
Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.
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)
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:
if(myString==null || myString.isEmpty()){ //do something }
or if blank spaces need to be detected as well:
if(myString==null || myString.trim().isEmpty()){ //do something }
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
public final class StringUtils{ private StringUtils() { } public static bool isNullOrEmpty(string s){ if(s==null || s.isEmpty()){ return true; } return false; } public static bool isNullOrWhiteSpace(string s){ if(s==null || s.trim().isEmpty()){ return true; } return false; } }
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With