Java String isBlank()

In this guide, you will learn about the String isBlank() method in Java programming and how to use it with an example.

1. String isBlank() Method Overview

Definition:

The isBlank() method is a part of the String class in Java. Introduced in Java 11, this method is used to check whether a given string is blank or not. A string is considered blank if it has a length of zero or only contains white spaces.

Syntax:

public boolean isBlank()

Parameters:

This method does not take any parameters.

Key Points:

- Returns true if the string is empty or contains only white spaces (including tabs and new lines).

- The method does not check for null, calling isBlank() on a null string will result in a NullPointerException.

- It is often used for validating user input in applications.

2. String isBlank() Method Example

public class IsBlankExample {
    public static void main(String[] args) {
        String str1 = "   ";
        String str2 = "\n\t   \t";
        String str3 = "Hello, World!";
        String str4 = "";

        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());
    }
}

Output:

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

Explanation:

In this example, four different strings are defined: str1 containing only spaces, str2 containing only white space characters like tabs and new lines, str3 containing alphanumeric characters, and str4 being an empty string. 

When the isBlank() method is called on these strings, it returns true for str1, str2, and str4 as they are either empty or only contain white space characters. For str3, which contains non-whitespace characters, the method returns false.

Comments