A Java method that tests if a String is null or blank

Problem: You’re working on a Java application, and you’re repeatedly performing a test to determine whether a String (or many strings) are either blank or null.

Solution

Create a simple Java method to perform this test for you. The following Java method returns true if a String is blank or null, otherwise it returns false:

private static boolean isNullOrBlank(String s)
{
  return (s==null || s.trim().equals(""));
}

Performing this test is so common in Java applications that I include this as a static method in one of the standard “utility” jar files that I carry with me from project to project. It makes it much easier to write code like this:

if (StringUtils.isNullOrBlank(myString))
{
  // do something important here
}

On a recent project I was working on where I used JSF to create a web user interface for Nagios I probably used this test 100 times or more.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.