23 Sep 2009
Empty or null String in Java
It’s such a common bit of code that crops up everywhere. That familiar line:
if(var != null && var.length() > 0)
There are slight variations. Some use
if(var != null && !var.equals(""))
They’re all there to achieve the same purpose: check whether a String is null or empty.
I’ve always thought “there really should be a utility for this”, but written the code anyway. Today, when faced with repeating this pattern about 10 times, I finally decided to go and check the Apache Commons Lang javadoc and see if there was such a method. Unsurprisingly, there is, in StringUtils.
There’s actually a few:
-
isBlank(String)
-
isEmpty(String)
-
isNotBlank(String)
-
isNotEmpty(String)
Very handy.