What's the better way to check if a String is empty than using String.trim().length() in Java 5/6?

I always like to use the Apache Commons StringUtils library. It has isEmpty() and is isBlank() which handles whitespace.

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

Not to mention the numerous other helpful methods in that class and the library in general.


I'd use the Guava CharMatcher class:

boolean onlyWhitespace = CharMatcher.WHITESPACE.matchesAllOf(input);

Okay guys, I have found it finally from PMD rules of InefficientEmptyStringCheck:

InefficientEmptyStringCheck:
Since: PMD 3.6
String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.

This is only a suggestion from PMD. To adopt it or not is depending on which has priority: the efficiency of programs or the time of programmers.

Tags:

Java

String