How to check if a string is empty or blank
Short answer
isEmpty() checks that a string has no characters, isBlank() checks that it contains nothing but whitespace:
void main() {
IO.println("".isEmpty());
IO.println(" ".isEmpty());
IO.println(" ".isBlank());
}Output:
true
false
trueThe string may be null
You cannot call a method on null, so check the reference first:
boolean isBlank(String text) {
return text == null || text.isBlank();
}
void main() {
IO.println(isBlank(null));
IO.println(isBlank(" \t "));
IO.println(isBlank("Anna"));
}Output:
true
true
falseA default value
Often an empty string should be replaced with a fallback value:
void main() {
String name = " ";
String shown = name.isBlank() ? "Guest" : name.strip();
IO.println("Hello, " + shown);
}Output:
Hello, GuestRemoving empty strings from a list
Filter strings with isBlank() in a stream:
void main() {
var lines = List.of("first", "", " ", "second");
var filled = lines.stream().filter(line -> !line.isBlank()).toList();
IO.println(filled);
}Output:
[first, second]Common mistake
Checking text.length() == 0 or text.isEmpty() on null throws an exception:
void main() {
String text = null;
IO.println(text.isEmpty());
}Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "<local1>" is nullPut text == null as the first condition — the || operator will not evaluate the second part.
Functions used in this recipe
- String.isEmpty() — Checks whether the string length is zero.
- String.isBlank() — Checks whether a string is empty or contains only whitespace.
- String.strip() — Removes any Unicode whitespace from both ends of a string.
- Objects.isNull() — Checks whether a value is null; its partner nonNull() does the opposite.