Java isBlank() method

1. Introduction

The syntax of the isBlank() method of String class is:

public boolean isBlank()

This method returns true if the string is empty or contains only white space codepoints, otherwise false. One important point to note here is the term white space codepoint.

A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’).
  • It is ‘\t’, U+0009 HORIZONTAL TABULATION.
  • It is ‘\n’, U+000A LINE FEED.
  • It is ‘\u000B’, U+000B VERTICAL TABULATION.
  • It is ‘\f’, U+000C FORM FEED.
  • It is ‘\r’, U+000D CARRIAGE RETURN.
  • It is ‘\u001C’, U+001C FILE SEPARATOR.
  • It is ‘\u001D’, U+001D GROUP SEPARATOR.
  • It is ‘\u001E’, U+001E RECORD SEPARATOR.
  • It is ‘\u001F’, U+001F UNIT SEPARATOR.

In simple words, if the string contains only no characters or only whitespaces, this method returns true, otherwise false.

2. Example

Let us now see isBlank() method with the examples.

public class IsBlankMethodExample {
    public static void main(String args[]) {
        // a non empty string
        String nonEmptyString = "hello";
        System.out.println("nonEmptyString.isBlank(): " + nonEmptyString.isBlank());

        //a string with only while spaces
        String withOnlyWhiteSpaces = "    ";
        System.out.println("withOnlyWhiteSpaces.isBlank(): " + withOnlyWhiteSpaces.isBlank());

        //a string with only while spaces
        String withOnlyNewLines = "\n";
        System.out.println("withOnlyNewLines.isBlank(): " + withOnlyNewLines.isBlank());


nonEmptyString.isBlank(): false
withOnlyWhiteSpaces.isBlank(): true
withOnlyNewLines.isBlank(): true

In this example, you should have observed that for both white spaces and new lines, isBlank() returns true.

3. Conclusion

In summary, isEmpty() checks for emptiness based on the number of characters, while isBlank() checks for emptiness considering both the number of characters and whether those characters are only white spaces.