Java String isBlank Example

1. Introduction

In this blog post, we explore the isBlank() method for String objects in Java. Introduced in Java 11, isBlank() is a handy method for checking whether a string is empty or contains only white space.

Definition

The String.isBlank() method in Java returns true if the string is empty or contains only white space characters. This method simplifies and makes more readable the common task of checking for empty or effectively empty strings.

2. Program Steps

1. Create several string examples: an empty string, a string with only white spaces, and a non-empty string.

2. Use isBlank() to check each string.

3. Display the results of these checks.

3. Code Program

public class StringIsBlankExample {
    public static void main(String[] args) {
        String emptyString = "";
        String whiteSpaceString = "   ";
        String nonEmptyString = "Java";

        // Checking if the strings are blank
        System.out.println("Is empty string blank? " + emptyString.isBlank());
        System.out.println("Is white space string blank? " + whiteSpaceString.isBlank());
        System.out.println("Is 'Java' string blank? " + nonEmptyString.isBlank());
    }
}

Output:

Is empty string blank? true
Is white space string blank? true
Is 'Java' string blank? false

Explanation:

1. Three strings are created: emptyString is an empty string, whiteSpaceString contains only white spaces, and nonEmptyString contains a regular non-empty string.

2. The isBlank() method is used to check each of these strings.

3. For emptyString and whiteSpaceString, isBlank() returns true, indicating that they are either empty or only contain white space characters.

4. For nonEmptyString, isBlank() returns false, as it contains actual characters other than white spaces.

5. This example demonstrates the usefulness of String.isBlank() in determining whether a string is empty or effectively empty in Java.


Comments