By Alvin Alexander. Last updated: October 15, 2016
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.