What is the ArrayList.isEmpty() method in Java?

The ArrayList.isEmpty() method in Java is used to check if a list is empty. An empty list means that it contains no elements.

Syntax

The ArrayList.isEmpty() method can be declared as shown in the code below:

public boolean isEmpty()

Return value

The ArrayList.isEmpty() method returns a boolean such that:

  • The return value is true if the list is empty.
  • The return value is false if the list is not empty.

Example

Consider the code below, which demonstrates the use of the ArrayList.isEmpty() method:

import java.util.ArrayList;
public class Example1 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>(5);
boolean empty = list1.isEmpty();
System.out.println("list1 is empty: " + empty);
list1.add(1);
list1.add(2);
list1.add(3);
empty = list1.isEmpty();
System.out.println("list1 is empty: " + empty);
}
}

Explanation

  • A list list1 is declared in line 6.
  • The ArrayList.isEmpty() method is used in line 8 to check if list1 is empty. The ArrayList.isEmpty() returns true because list1 contains no elements.
  • Three elements are added in list1 in lines 11-13 using the add() method.
  • The ArrayList.isEmpty() method is used in line 15 to check if list1 is empty. The ArrayList.isEmpty() returns false because list1 now contains three elements.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources