Ways to check if a String is null and if it’s not, if it’s blank

Quick clarification: the empty String is “”. ” ” is not considered an empty String, but it’s a blank one. If it contains nothing but whitespace characters, it’s a blank String.

If you don’t want to use any third-party libraries, you should do it the long way:

if((s != null) && (!s.trim().equals(""))

If you don’t mind bringing over a third party library into your project classpath, you have a couple of clear options.

With Apache Commons Library:




The difference between the first and the second being in the fact that isEmpty(s) will return false if s is a String composed of spaces, like ”   “, whereas isBlank(s) will detect that case and return true for it. Doing isEmpty(s.trim()) would skip that problem, but it would create a new (and unnecessary) String object.

With Guava:


In this case, doing trim() is necessary, since the method isNullOrEmpty does not return true if it does not receive the empty String.

Leave a Reply

Your email address will not be published. Required fields are marked *