Is a String Empty?

Prior to JDK 6, we can check if a string is empty in 2 ways:
  • if(s != null && s.length() == 0)
  • if(("").equals(s))
Checking its length is more readable and may be a little faster. Starting from JDK 6, String class has a new convenience method isEmpty():
boolean isEmpty()
Returns true if, and only if, length() is 0.
It is just a shorthand for checking length. Of course, if the String is null, you will still get NullPointerException. I don't see much value in adding this convenience method. Instead, I'd like to see a static utility method that also handle null value:
public static boolean notEmpty(String s) {
return (s != null && s.length() > 0);
}

Followers

Pageviews Last 7 Days