How do I check for an empty string?

StringUtils.isBlank() method check to see is the string contains only whitespace characters, empty or has a null value. If these conditions are true the strings are considered blank.

There’s also a StringUtils.isEmpty(), only this method doesn’t check for whitespaces-only string. For checking the opposite condition there are StringUtils.isNotBlank() and StringUtils.isNotEmpty().

Using these methods we can avoid repeating the code for checking empty string which can include more code to type then using these handy methods.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class CheckEmptyString {
    public static void main(String[] args) {
        String var1 = null;
        String var2 = "";
        String var3 = "    \t\t\t";
        String var4 = "Hello World";

        System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
        System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
        System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
        System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));

        System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
        System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
        System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
        System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));

        System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
        System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
        System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
        System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));

        System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
        System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
        System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
        System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));

The result of our program are:

var1 is blank? = true
var2 is blank? = true
var3 is blank? = true
var4 is blank? = false
var1 is not blank? = false
var2 is not blank? = false
var3 is not blank? = false
var4 is not blank? = true
var1 is empty? = true
var2 is empty? = true
var3 is empty? = false
var4 is empty? = false
var1 is not empty? = false
var2 is not empty? = false
var3 is not empty? = true
var4 is not empty? = true

Maven Dependencies


Maven Central



  1. Have you ever run the program once?

    var3 is blank? = true

    This is incorrect. By the way, you should use commons-lang3 instead of the older version.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.