How to Check If a String Is Blank in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is blank in Java. You will explore the isBlank() method, introduced in Java 11, which efficiently determines if a string is empty or contains only whitespace characters.

Through hands-on examples, you will first use isBlank() to check various string types. Then, you will learn how to combine isBlank() with a null check for robust string validation. Finally, you will compare the behavior of isBlank() and isEmpty() to understand their key differences.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/if_else -.-> lab-559985{{"How to Check If a String Is Blank in Java"}} java/strings -.-> lab-559985{{"How to Check If a String Is Blank in Java"}} java/string_methods -.-> lab-559985{{"How to Check If a String Is Blank in Java"}} end

Use isBlank() to Check for Blank String

In this step, you will learn how to use the isBlank() method in Java to check if a string is blank. A blank string is a string that contains only whitespace characters (spaces, tabs, newlines) or is empty.

The isBlank() method was introduced in Java 11 and is a convenient way to check for blank strings. It returns true if the string is empty or contains only whitespace, and false otherwise.

Let's create a simple Java program to demonstrate the isBlank() method.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            String str1 = ""; // Empty string
            String str2 = "   "; // String with only spaces
            String str3 = "Hello"; // Non-blank string
            String str4 = " Hello "; // String with leading/trailing spaces
    
            System.out.println("Is str1 blank? " + str1.isBlank());
            System.out.println("Is str2 blank? " + str2.isBlank());
            System.out.println("Is str3 blank? " + str3.isBlank());
            System.out.println("Is str4 blank? " + str4.isBlank());
        }
    }

    In this code:

    • We declare four different strings: an empty string, a string with only spaces, a non-blank string, and a string with leading/trailing spaces.
    • We use str.isBlank() to check if each string is blank and print the result.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile the program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. If not, use the command cd ~/project. Then, compile the code using the javac command:

    javac HelloJava.java

    If there are no errors, a HelloJava.class file will be created in the ~/project directory.

  5. Finally, run the compiled program using the java command:

    java HelloJava

    You should see the following output:

    Is str1 blank? true
    Is str2 blank? true
    Is str3 blank? false
    Is str4 blank? false

    As you can see, isBlank() correctly identifies the empty string (str1) and the string with only spaces (str2) as blank, while str3 and str4 are considered non-blank because they contain non-whitespace characters.

Combine isBlank() with Null Check

In the previous step, you learned how to use isBlank() to check for empty or whitespace-only strings. However, isBlank() will throw a NullPointerException if the string variable is null. In real-world applications, it's common to encounter null strings, so it's important to handle them gracefully.

To safely check if a string is either null or blank, you should combine a null check with the isBlank() method. The most common way to do this is using an if statement:

if (str == null || str.isBlank()) {
    // The string is null or blank
} else {
    // The string is not null and not blank
}

Let's modify our program to include a null string and demonstrate how to handle it.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the current code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String str1 = ""; // Empty string
            String str2 = "   "; // String with only spaces
            String str3 = "Hello"; // Non-blank string
            String str4 = null; // Null string
    
            System.out.println("Is str1 null or blank? " + (str1 == null || str1.isBlank()));
            System.out.println("Is str2 null or blank? " + (str2 == null || str2.isBlank()));
            System.out.println("Is str3 null or blank? " + (str3 == null || str3.isBlank()));
            System.out.println("Is str4 null or blank? " + (str4 == null || str4.isBlank()));
        }
    }

    In this updated code:

    • We added a null string variable str4.
    • We use the condition str == null || str.isBlank() to check if each string is either null or blank. The || operator means "or". If the first part (str == null) is true, the second part (str.isBlank()) is not even checked, which prevents the NullPointerException.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see the following output:

    Is str1 null or blank? true
    Is str2 null or blank? true
    Is str3 null or blank? false
    Is str4 null or blank? true

    This output shows that our combined check correctly identifies the empty string, the string with spaces, and the null string as "null or blank", while the non-blank string is correctly identified as "not null or blank".

Combining the null check with isBlank() is a robust way to handle various string states in your Java programs.

Compare isBlank() and isEmpty()

In the previous steps, you've used isBlank() to check for strings that are empty or contain only whitespace. You might have also heard of the isEmpty() method in Java. In this step, we will compare isBlank() and isEmpty() to understand the difference between them.

The isEmpty() method has been available in Java since version 1.0. It returns true only if the string has a length of 0 (i.e., it's an empty string ""). It returns false for any other string, including strings that contain only whitespace.

Let's modify our program one last time to use both isBlank() and isEmpty() and see how they behave with different types of strings.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the current code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            String str1 = ""; // Empty string
            String str2 = "   "; // String with only spaces
            String str3 = "Hello"; // Non-blank string
            String str4 = null; // Null string
    
            System.out.println("--- Using isBlank() ---");
            System.out.println("Is str1 blank? " + (str1 == null || str1.isBlank()));
            System.out.println("Is str2 blank? " + (str2 == null || str2.isBlank()));
            System.out.println("Is str3 blank? " + (str3 == null || str3.isBlank()));
            // Note: We still need the null check before calling isBlank()
            System.out.println("Is str4 blank? " + (str4 == null || str4.isBlank()));
    
            System.out.println("\n--- Using isEmpty() ---");
            // Note: We also need a null check before calling isEmpty()
            System.out.println("Is str1 empty? " + (str1 == null || str1.isEmpty()));
            System.out.println("Is str2 empty? " + (str2 == null || str2.isEmpty()));
            System.out.println("Is str3 empty? " + (str3 == null || str3.isEmpty()));
            System.out.println("Is str4 empty? " + (str4 == null || str4.isEmpty()));
        }
    }

    In this code:

    • We added sections to demonstrate both isBlank() and isEmpty().
    • We use the combined null check (str == null || ...) before calling both isBlank() and isEmpty() to prevent NullPointerException.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see the following output:

    --- Using isBlank() ---
    Is str1 blank? true
    Is str2 blank? true
    Is str3 blank? false
    Is str4 blank? true
    
    --- Using isEmpty() ---
    Is str1 empty? true
    Is str2 empty? false
    Is str3 empty? false
    Is str4 empty? true

    From the output, you can observe the key difference:

    • isBlank() returns true for both empty strings ("") and strings with only whitespace (" ").
    • isEmpty() returns true only for empty strings (""). It returns false for strings with only whitespace (" ").

    Both methods require a null check before being called on a potentially null string.

In summary:

  • Use isEmpty() when you only want to check if a string has zero length.
  • Use isBlank() when you want to check if a string is empty or contains only whitespace characters.

Understanding the difference between these two methods is crucial for writing correct and robust string handling code in Java.

Summary

In this lab, you learned how to check if a string is blank in Java using the isBlank() method, which was introduced in Java 11. You practiced using isBlank() on different types of strings, including empty strings, strings with only whitespace, and strings with content. You also compiled and ran a simple Java program to demonstrate the functionality of isBlank().