How to Check Empty or Blank Strings in Java

Published on 2022-02-16

In this article, we will look what is the use of empty or blank strings in the Java programming language and try to understand how they are more important to us with the help of some examples.

Java

Java is a collection of computer software and standards developed by Sun Microsystems, which was later bought by Oracle Corporation. It’s used to build and deploy application software across different platforms.

Strings in Java

Text in Java is stored using strings. A String variable comprises a collection of characters enclosed in double quotations. In Java, a String is really an object that has methods for performing string operations. The length() method, for example, is used to determine the length of a string.

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

Checking If a String is Empty or Blank

There is a distinction between empty and blank Strings in Java:

  • An empty string is a String object that has a value set to it but has no length.
  • A blank string contains only whitespaces because it has an assigned value and isn’t 0 length.

String emptyString = "";

String blankString = " ";

There are plenty of methods to check for empty or blank strings in Java. Let’s discuss a few:

Using the length of the String

The length() function is the best technique to see if a string is empty or not. This function only returns the number of characters in the char array that make up the text. You can reasonably assume that the String is empty if the count or length is 0.

public boolean isEmpty(String str) {
    return str.equals("");  //NEVER do this
}

public boolean isEmpty(String str) {
    return str.length()==0;   //Correct way to check empty
}

It’s neither null nor empty since the String is blank. Because whitespace is a Character, we can’t tell if a String includes just whitespaces or any other character based on its length alone.

The length() method, as you can see, is just a getter that returns the number of characters in an array. As a result, finding the length of a string requires extremely little CPU time. Furthermore, a String with a length of 0 is always empty. Before determining if a string is empty, the equals() method performs a huge number of statements. It uses the while loop after checking for references, typecasting if necessary, and generating temporary arrays. As a result, many CPU cycles are squandered, checking a fundamental condition.

Using Java String isEmpty() Method

The isEmpty() function solely determines whether or not the String is empty. If you wish to verify whether a String is null or empty on both sides, you may do so as demonstrated in the example below.

public class Example{
    public static void main(String args[]) {
        String str1 = null;
        String str2 = "beginnersbook";
        if(str1 == null || str1.isEmpty()) {
            System.out.println("String str1 is empty or null");
        } else {
            System.out.println(str1);
        }

        if(str2 == null || str2.isEmpty()) {
            System.out.println("String str2 is empty or null");
        } else {
            System.out.println(str2);
        }
    }
}

=>
String str1 is empty or null
beginnersbook

With Apache Commons

If it’s permissible to add dependencies, we can use Apache Commons Lang. There are several Java assistances in this. If we’re using Maven, we’ll need to add the commons-lang3 dependency to our pom:

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

This includes, among other things, StringUtils. This class has several methods, including isEmpty, isBlank, and others.

StringUtils.isBlank(string)

This function is the same as our isBlankString function. It is null-safe and checks for whitespaces.

With Guava

<dependency >
    <groupId >com.google.guava </groupId >
    <artifactId >guava </artifactId >
    <version >29.0-jre </version >
</dependency >

Guavas Strings class comes with a method Strings.isNullOrEmpty

Strings.isNullOrEmpty(string)

It examines if a string is null or empty, but it does not check for strings that are merely whitespace.

Using the StringUtils Class

The Apache Commons is a popular Java library with additional features. Apache Commons provides StringUtils as one of its classes. This class, like Java.lang.String includes methods for working with Strings.

Let’s add Apache Commons as a dependency because we’ll be utilizing it in this approach:

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

In case of Gradle

compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11'

StringUtils methods are entirely null-safe, which is one of the most significant distinctions between StingUtils and String methods. There are a few more ways for this, such as StringUtils.isEmpty() and StringUtils.isBlank().

String nullString = null;
if(nullString == null) {
    System.out.println("String is null");
} else if(StringUtils.isEmpty(nullString)) {
    System.out.println("String is empty");
} else if(StringUtils.isBlank(nullString)) {
    System.out.println("String is blank");
}

=>
String is null

In addition to these, there are inverse methods: However, you may get the same functionality as StringUtils.isNotEmpty() and StringUtils.isNotBlank() by using the NOT (!) operator:

if(StringUtils.isNotEmpty("")) {
    System.out.println("String is not empty");
}

// Equivalent to
if(!StringUtils.isEmpty("")) {
    System.out.println("String is not empty");
}

Understanding with Examples

Following are some examples in which we will check whether a java String is empty or blank.

Example #1

class Main {
    public static void main(String[] args) {
        // create null, empty, and regular strings
        String strng1 = null;
        String strng2 = "";
        String strng3 = "  ";

        // check if strng1 is null or empty
        System.out.println("strng1 is " + isNullEmpty(strng1));
        // check if strng2 is null or empty
        System.out.println("strng2 is " + isNullEmpty(strng2));
        // check if strng3 is null or empty
        System.out.println("strng3 is " + isNullEmpty(strng3));
    }

    // method to check if string is null or empty
    public static String isNullEmpty(String strng) {
        // check if string is null
        if (strng == null) {
            return "NULL";
        }
    } else if(strng.isEmpty()) {
        return "EMPTY";
    } else {
        return "neither NULL nor EMPTY";
    }
}

=>
strng1 is NULL
strng2 is EMPTY
strng3 is neither NULL nor EMPTY

Example #2

public class StringNullOrBlank  {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "  ";
        if (isNullOrBlank(str1)) {
            System.out.println("str1 is null or blank.");
        } else {
            System.out.println("str1 is not null or blank.");
        }

        if (isNullOrBlank(str2)) {
            System.out.println("str2 is null or blank.");
        } else {
            System.out.println("str2 is not null or blank.");
        }

    public static boolean isNullOrBlank(String str) {
        if (str != null && !str.trim().isEmpty()) {
            return false;
        }
        return true;
    }
}

=>
str1 is null or blank.str2 is null or blank.

Example #3

// Java Program to check if
// the String is empty in Java
class Alpha {
    // Methods to verify if the String is empty
    public static boolean isStringEmpty(String str) {
        // verify whether the string is empty or not
        // using isEmpty() method
        // and return the result
        if (str.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    // Driver code
    public static void main(String[] args) {
        String str1 = "Hello My World";
        String str2 = "";
        System.out.println("Is string \"" + str1
        + "\" empty? "
        + isStringEmpty(str1));
        System.out.println("Is string \"" + str2
        + "\" empty? "
        + isStringEmpty(str2));
    }
}

=>
Is string "Hello My World" empty? False Is string "" empty? True

Example #4

class Main {
    public static void main(String[] args) {
        // create a string with white spaces
        String strng = "    ";
        // check if strng1 is null or empty
        System.out.println("strng is " + isNullEmpty(strng));
    }

    // method to check whether the string is null or empty
    public static String isNullEmpty(String strng) {
        // check if string is null
        if (strng == null) {
            return "NULL";
        } else if (strng.trim().isEmpty()) {
            return "EMPTY";
        } else {
            return "neither NULL nor EMPTY";
        }
    }
}

=>
Strng is empty

Example #5

import org.apache.commons.lang3.StringUtils;
public class StringUtilsIsEmptyExample {
    public static void main(String[] args) {
        String example1 = null;
        String example2 = "";
        String example3 = "          ";
        String example4 = "testString";
        boolean result1 = StringUtils.isEmpty(example1);
        boolean result2 = StringUtils.isEmpty(example2);
        boolean result3 = StringUtils.isEmpty(example3);
        boolean result4 = StringUtils.isEmpty(example4);
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
    }
}

=>
True
True
False
False

Conclusion

There are various methods to determine whether or not a string is empty. We typically want to know if a string is empty or just contains whitespace characters. The most practical approach is to use Apache Commons Lang, which contains helpers such as StringUtils.isBlank. If we want to stick to normal Java, we may use a combination of String.trim and either String.isEmpty or String.length.

The length() function is only a getter method that returns the number of characters in an array. As a result, finding the length of a string does not consume many CPU cycles. And any String with length 0 will always be an empty string. In contrast, the equals() function requires a number of statements before deciding if a string is empty. It does a reference check, typecasting if required, creates temporary arrays, and then employs a while loop. Hence, there is a significant waste of CPU cycles in order to validate a basic condition.