The String.isEmpty() method returns true if, and only if, the string has a length of zero (length() == 0).
Zero-Length Checks & Modern Alternatives: It executes in O(1) time. To measure character size directly, see length(). For whitespace-tolerant validation, explore modern Java's isBlank(). To sanitize outer space padding before emptiness checks, see trim(), or compare string equality with equals().
The isEmpty() method takes no arguments and is defined in java.lang.String:
// Formal signature of String.isEmpty() in java.lang.String
public boolean isEmpty()
| Signature Element | Type | Operational Property |
|---|---|---|
| Parameters | None | Takes no arguments; called directly on the target string object. |
| Return Value | boolean |
Returns true if length() == 0; returns false otherwise. |
| Time Complexity | O(1) |
Constant time. Performs a direct zero comparison against precomputed length. |
Testing empty strings, populated strings, and whitespace strings:
String str1 = "";
String str2 = "plus2net";
String str3 = " ";
System.out.println("str1.isEmpty(): " + str1.isEmpty()); // true
System.out.println("str2.isEmpty(): " + str2.isEmpty()); // false
System.out.println("str3.isEmpty(): " + str3.isEmpty()); // false (contains 3 spaces!)Terminal Output:
str1.isEmpty(): true
str2.isEmpty(): false
str3.isEmpty(): false
Understanding the distinction between unallocated memory, zero characters, and whitespace:
| State | Example Value | str.length() |
str.isEmpty() |
str.isBlank() (Java 11+) |
|---|---|---|---|---|
| Null | null |
Throws NPE |
Throws NPE |
Throws NPE |
| Empty | "" |
0 |
true |
true |
| Blank | " " |
3 |
false |
true |
| Populated | "Java" |
4 |
false |
false |
Java 11 introduced isBlank() to address strings that contain only invisible whitespace:
String empty = "";
String whitespace = " \t\n";
String populated = "Java";
// isEmpty(): Checks if length() == 0 strictly
System.out.println("empty.isEmpty(): " + empty.isEmpty()); // true
System.out.println("whitespace.isEmpty(): " + whitespace.isEmpty()); // false
// isBlank() (Java 11+): Checks if length() == 0 OR only whitespace
System.out.println("empty.isBlank(): " + empty.isBlank()); // true
System.out.println("whitespace.isBlank(): " + whitespace.isBlank()); // true
System.out.println("populated.isBlank(): " + populated.isBlank()); // falseTerminal Output:
empty.isEmpty(): true
whitespace.isEmpty(): false
empty.isBlank(): true
whitespace.isBlank(): true
populated.isBlank(): false
Invoking isEmpty() on a null reference immediately causes a NullPointerException. Always guard with short-circuit logical operators (&&):
String uninitialized = null;
// RISKY: Calling isEmpty() on null throws NullPointerException
try {
System.out.println(uninitialized.isEmpty());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null string!");
}
// SAFE APPROACH 1: Short-circuit null check
boolean hasText = (uninitialized != null && !uninitialized.isEmpty());
System.out.println("Safe hasText check: " + hasText); // falseTerminal Output:
Caught NullPointerException on null string!
Safe hasText check: false
Validating whether essential user inputs are present and contain actual non-whitespace characters:
public class FormValidator {
public static boolean validateRequiredField(String fieldName, String value) {
if (value == null || value.trim().isEmpty()) {
System.out.println("Validation Error: " + fieldName + " is required and cannot be empty.");
return false;
}
System.out.println("Validation Success: " + fieldName + " is valid.");
return true;
}
public static void main(String[] args) {
validateRequiredField("Username", "john_doe"); // valid
validateRequiredField("Email", " "); // error
}
}Terminal Output:
Validation Success: Username is valid.
Validation Error: Email is required and cannot be empty.
Providing clean fallback strings when user profile inputs or configuration keys are empty:
public class DefaultFallbackHelper {
public static String getOrDefault(String input, String fallback) {
if (input == null || input.isEmpty()) {
return fallback;
}
return input;
}
public static void main(String[] args) {
System.out.println("User 1: " + getOrDefault("Alice", "Anonymous")); // Alice
System.out.println("User 2: " + getOrDefault("", "Anonymous")); // Anonymous
System.out.println("User 3: " + getOrDefault(null, "Anonymous")); // Anonymous
}
}Terminal Output:
User 1: Alice
User 2: Anonymous
User 3: Anonymous
Sanitizing text lines from user submissions or file uploads by stripping empty rows:
List<String> rawLines = List.of("First line", "", "Third line", " ", "Fifth line");
// Filter out all empty or whitespace-only lines
List<String> cleanLines = new ArrayList<>();
for (String line : rawLines) {
if (line != null && !line.trim().isEmpty()) {
cleanLines.add(line);
}
}
System.out.println("Cleaned lines: " + cleanLines);Terminal Output:
Cleaned lines: [First line, Third line, Fifth line]
Assuming " ".isEmpty() evaluates to true is a major source of bugs in form validation. Because spaces are characters, length is 3 and isEmpty() returns false. In Java 11+, use isBlank(), or in older Java use str.trim().isEmpty().
Calling str.isEmpty() when str == null crashes the application. Always verify str != null first or use Apache Commons StringUtils.isEmpty(str).
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringIsEmptyFullDemo {
public static void main(String[] args) {
String emptyStr = "";
String textStr = "plus2net";
// 1. Verify empty string returns true
if (emptyStr.isEmpty()) {
System.out.println("Check 1 Passed: Empty string correctly identified.");
}
// 2. Verify equivalence to length() == 0
if (emptyStr.isEmpty() == (emptyStr.length() == 0)) {
System.out.println("Check 2 Passed: isEmpty() exactly matches length() == 0.");
}
// 3. Verify non-empty string returns false
if (!textStr.isEmpty()) {
System.out.println("Check 3 Passed: Populated string correctly evaluated to false.");
}
// 4. Verify safe null checking guard
String nullStr = null;
boolean safeCheck = (nullStr != null && !nullStr.isEmpty());
if (!safeCheck) {
System.out.println("Check 4 Passed: Null-safe guard bypassed exception.");
}
System.out.println("All String.isEmpty() verification checks passed successfully!");
}
}Terminal Output:
Check 1 Passed: Empty string correctly identified.
Check 2 Passed: isEmpty() exactly matches length() == 0.
Check 3 Passed: Populated string correctly evaluated to false.
Check 4 Passed: Null-safe guard bypassed exception.
All String.isEmpty() verification checks passed successfully!
They have identical performance. Inside Java's standard library, isEmpty() is implemented simply as return length() == 0;.
isEmpty() was added in Java 6 to replace manual length checks and provide more expressive, readable code.
No. isEmpty() takes zero arguments. Some older tutorials incorrectly show parameters; it strictly operates on the calling string instance.
Use str != null && !str.isEmpty(). The short-circuit && operator prevents NullPointerException if str is null.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.