Thursday, November 8, 2007

Java's String.isEmpty() Method (Java SE 6)

The String.isEmpty() method added to Java SE 6 is another example of syntactic sugar that does make code a little more readable. Because Java Strings are used so frequently, even this small improvement is appreciated. The isEmpty() method only returns true if calling the length() method on the String returns zero. It is important to note, however, that isEmpty does not check for null. In other words, the following example would result in a NullPointerException:

String someStr = null;
if ( someStr.isEmpty() )  // will throw NullPointerException
{
   System.err.println("I like the newly added isEmpty() method!");
}

For significant additional Java String support, see the Apache Commons StringUtils library.

No comments: