Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.isEmpty() — checking whether a list is empty

`List.isEmpty()` returns `true` when a list has no elements. Use the result to choose a branch or to guard a read of the first or last element.

Version: Java SE 21

Syntax

boolean isEmpty(); // declaration in java.util.List<E>
list.isEmpty()     // instance call; true when the list has no elements
!list.isEmpty()    // true when the list has at least one element

List.isEmpty names the method on the java.util.List interface; List.isEmpty() shows that it takes no arguments. It is an instance method, not a static method: call it as list.isEmpty(). It returns a boolean: true for zero elements and false for one or more. It does not modify the list. It tests the same condition as list.size() == 0 but states the intent directly.

An empty list is not a null reference. Calling list.isEmpty() on a null reference throws NullPointerException. If the list implementation allows null elements, a list with one such element is not empty.

Use if (!list.isEmpty()) before list.get(0) or before reading the first and last elements with list.getFirst() and list.getLast() in Java 21. On an empty list, get(0) throws IndexOutOfBoundsException, whereas both endpoint methods throw NoSuchElementException. The check only protects the read if the list does not become empty between the check and the read.

Examples

import java.util.List;

public class ListIsEmptyDemo {
    public static void main(String[] args) {
        showStatus("Alice", List.of());
        showStatus("Bob", List.of("review overdue"));
    }

    private static void showStatus(String name, List<String> reasons) {
        if (reasons.isEmpty()) {
            System.out.println(name + ": active");
        } else {
            System.out.println(name + ": inactive (" + reasons.get(0) + ")");
        }
    }
}

Result

Alice: active
Bob: inactive (review overdue)

Alice stays active because her list of deactivation reasons is empty. Bob is inactive because his list contains a reason. The program reads the first reason with `get(0)` only in the non-empty branch.

Related lessons

  • Java · Lesson 10 · Advanced · Version: 2
  • Java · Lesson 58 · Basic · Version: 2
  • Java · Lesson 34 · Intermediate · Version: 2
  • Java · Lesson 41 · Intermediate · Version: 2

Sources