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".
"".isEmpty(); // true " ".isEmpty(); // false " ".isBlank(); // true
Try it
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.
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
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(). Writes == null || s.isBlank(), or use a helper from a library you already depend on. isEmpty()is notlength() == 0plus anything. It is the same check, just more readable, and is also defined byCharSequencesince Java 15.- Do not use
s == "". Reference comparison on strings is unreliable; useisEmpty()orequals(""). - Trim first only if you need the trimmed value. If you only need the yes/no answer,
isBlank()avoids allocating a stripped copy. - For
Optionalflows,Optional.ofNullable(s).filter(x -> !x.isBlank())yields an emptyOptionalfor null and blank values. - Java 8 and 10: there is no
isBlank(); uses.trim().isEmpty(), which treats any char up to U+0020 as space.