Pages Navigation Menu

Coding is much easier than you think

Best way to check a string against null in java?

Best way to check a string against null in java?

 
String in Java is considered empty if its not null and it’s length is 0. But before checking length you should verify that String is not null because calling length() on null String will result in NullPointerException.
 
Apache commons lang has a StringUtils class which has static method isEmpty(String input), which returns true if input string is null or has length equal to zero.
 
Output of StringUtils for various input :

StringUtils.isEmpty("value")   = false
StringUtils.isEmpty(" ")       = false
StringUtils.isEmpty("")        = true
StringUtils.isEmpty(null)      = true

 

About Mohaideen Jamil