Wednesday, October 17, 2007

String empty check is more easy now with JDK6

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);
}


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;
}

No comments:

Post a Comment

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...