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

Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.