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 condition is true that the string considered blank.

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

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

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class CheckEmptyString {
    public static void main(String[] args) {
        String var1 = null;
        String var2 = "";
        String var3 = "    ttt";
        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

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply