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:
if(StringUtils.isEmpty(s))
Or:
if(StringUtils.isBlank(s))
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:
if(Strings.isNullOrEmpty(s.trim()))
In this case, doing trim() is necessary, since the method isNullOrEmpty does not return true if it does not receive the empty String.