How do I check for an empty string?

package org.kodejava.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class EmptyStringCheckDemo {
    public static void main(String[] args) {
        // Create some variable to hold some empty string, contains only
        // whitespaces and words.
        String one = "";
        String two = "\t\r\n";
        String three = "     ";
        String four = null;
        String five = "four four two";

        // We can use StringUtils class for checking if a string is empty or not
        // using StringUtils.isBlank() method. This method will return true if
        // the tested string is empty, contains whitespaces only or null.
        System.out.println("Is one empty? " + StringUtils.isBlank(one));
        System.out.println("Is two empty? " + StringUtils.isBlank(two));
        System.out.println("Is three empty? " + StringUtils.isBlank(three));
        System.out.println("Is four empty? " + StringUtils.isBlank(four));
        System.out.println("Is five empty? " + StringUtils.isBlank(five));

        // On the other side, the StringUtils.isNotBlank() methods complement
        // the previous method. It will check if a tested string is not empty.
        System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
        System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
        System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
        System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
        System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
    }
}

Here is the result:

Is one empty? true
Is two empty? true
Is three empty? true
Is four empty? true
Is five empty? false
Is one not empty? false
Is two not empty? false
Is three not empty? false
Is four not empty? false
Is five not empty? true

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

Wayan

1 Comments

  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.

    Reply

Leave a Reply

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