Showing posts with label empty. Show all posts
Showing posts with label empty. Show all posts

Sunday, June 12, 2011

String empty check is more easy now with JDK6 and StringUtils

Prior to JDK 6, we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)

//OR

if(("").equals(s))

Support from JDK6
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);
}



Support from StringUtils
Another option, use StringUtils.isEmpty(String str) of Apache commons , can be downloaded from - http://commons.apache.org/

It checks for null string also and return true for empty
public static boolean isEmpty(String str) {
return str == null str.length() == 0;
}


Chitika