Java String.isEmpty
Test whether a field contains zero characters.
A simple example
String.isEmpty
- Start with ""
- Do this Check whether any characters exist
- Result Empty
class Main {
public static void main(String[] args) throws Exception {
System.out.println("".isEmpty());
}
}
true
Syntax
public boolean isEmpty()
JDK 21 method signatures (1)
public boolean isEmpty()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck an optional delivery note
A form accepts an optional note typed or pasted by a customer or student. Decide whether the field contains meaningful text before displaying it to the person who will act on the request.
class Main {
public static void main(String[] args) throws Exception {
String note = "";
System.out.println(note.isEmpty());
}
}
true
An untouched note has length zero.
Distinguish spaces from an empty answer
A form can look blank even when its field contains a space. Examine the stored input before marking the answer as missing, because an empty string and whitespace can require separate checks.
class Main {
public static void main(String[] args) throws Exception {
String answer = " ";
System.out.println(answer.isEmpty());
}
}
false
Two spaces still occupy two character positions.
Accept a written handover
A night worker types a short handover message. The clerk first checks whether the field contains any characters at all. Is the supplied field empty?
What to watch for
A field containing only spaces is nonempty. Use isBlank when whitespace should count as absent.