Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.isEmpty — checking for an empty string

String.isEmpty() checks whether a string has length zero. It does not treat spaces as empty text and requires a non-null reference; use isBlank() to check for empty text or text consisting only of whitespace.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public boolean isEmpty()
// Usage: text.isEmpty()

String.isEmpty is an instance method with the signature public boolean isEmpty(). It takes no arguments and returns true exactly when length() == 0; otherwise, it returns false. Call it on an object, such as text.isEmpty(), rather than as a static method.

The empty string "" contains no characters. The string " " contains a space, so its isEmpty() returns false. The method does not remove whitespace. To accept empty text or text containing only whitespace recognized by Character.isWhitespace, use isBlank().

null is not an empty string. Calling text.isEmpty() when text is null throws NullPointerException. The condition text != null && text.isEmpty() safely checks whether an existing string is empty; it evaluates to false for null.

The example demonstrates these distinctions. This description targets Java SE 21; it does not attest the production runtime version or claim that the example has been executed.

Examples

public class Main {
    public static void main(String[] args) {
        System.out.println("".isEmpty());
        System.out.println(" ".isEmpty());
        System.out.println("Java".isEmpty());
        System.out.println(" ".isBlank());

        String text = null;
        System.out.println(text != null && text.isEmpty());
    }
}

Result

true
false
false
true
false

The expected output shows that `""` is empty, `" "` is blank but not empty, and `"Java"` is not empty. For `null`, `text != null && text.isEmpty()` evaluates to `false` without calling `isEmpty()`.

Sources