Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

Java String.isEmpty() and isBlank() methods

Reference for Java String.isEmpty() and isBlank() (Java 11): how they differ, what counts as whitespace, and how to check for null as well.

isEmpty() answers "does this string have zero characters?" and isBlank() answers "is it empty or made up only of whitespace?" Both return a boolean and both throw NullPointerException when called on null.

isEmpty() has been in Java since version 6; isBlank() was added in Java 11. Use isBlank() for form fields and user input, where a string of spaces should count as "nothing entered".

Java
"".isEmpty();       // true
"  ".isEmpty();     // false
"  ".isBlank();     // true

Try it

Java Empty versus blank

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Validating input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public boolean isEmpty()   // since 1.6
public boolean isBlank()   // since 11

Returns: isEmpty() is true when length() == 0. isBlank() is true when the string is empty or every character is whitespace according to Character.isWhitespace(int).

Throws: NullPointerException if the receiver is null.

Usage notes

  • Whitespace is defined by Character.isWhitespace. That includes space, tab, line feed, carriage return and the Unicode space separators, with one catch: the non-breaking spaces (ย , โ€‡, โ€ฏ) are not whitespace, so a string of only those is not blank.
  • No built-in null check. Java has no isNullOrEmpty(). Write s == null || s.isBlank(), or use a helper from a library you already depend on.
  • isEmpty() is not length() == 0 plus anything. It is the same check, just more readable, and is also defined by CharSequence since Java 15.
  • Do not use s == "". Reference comparison on strings is unreliable; use isEmpty() or equals("").
  • Trim first only if you need the trimmed value. If you only need the yes/no answer, isBlank() avoids allocating a stripped copy.
  • For Optional flows, Optional.ofNullable(s).filter(x -> !x.isBlank()) yields an empty Optional for null and blank values.
  • Java 8 and 10: there is no isBlank(); use s.trim().isEmpty(), which treats any char up to U+0020 as space.