The isEmpty() method of the ArrayList class is used to check whether an ArrayList contains any elements. It returns true if the list has no elements; otherwise, it returns false.
- Checks whether an ArrayList is empty.
- Returns a boolean value without modifying the list.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an empty ArrayList of Integers
ArrayList<Integer> n = new ArrayList<>();
// Checking if the ArrayList is empty
boolean res = n.isEmpty();
System.out.println("" + res);
// Adding an element
// to the ArrayList
n.add(21);
// Checking again if the
// ArrayList is empty
res = n.isEmpty();
System.out.println("" + res);
}
}
Output
true false
Explanation: Initially, the ArrayList contains no elements, so isEmpty() returns true. After adding an element, the list is no longer empty, so it returns false.
Syntax
public boolean isEmpty()
Return Type: It returns a boolean value, true if the list is empty, otherwise false.
Example: Using isEmpty() with an ArrayList of Strings
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();
System.out.println("Is list empty? " + fruits.isEmpty());
fruits.add("Mango");
fruits.add("Apple");
System.out.println("Is list empty? " + fruits.isEmpty());
}
}
Output
Is list empty? true Is list empty? false
Explanation: The isEmpty() method checks whether the ArrayList contains any elements. After adding two strings, the method returns false.
Example: Using isEmpty() with Custom Objects
import java.util.ArrayList;
class Student {
String name;
Student(String name) {
this.name = name;
}
}
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Student objects
ArrayList<Student> students = new ArrayList<>();
System.out.println(students.isEmpty());
students.add(new Student("Alice"));
System.out.println(students.isEmpty());
}
}
Output
true false
Explanation: The isEmpty() method works with any type of ArrayList, including custom objects. It returns true when the list has no objects and false after an object is added.
Difference Between isEmpty() and size()
| isEmpty() | size() |
|---|---|
Returns true if the list is empty. | Returns the number of elements in the list. |
Return type is boolean. | Return type is int. |
| Used to check whether a list has elements. | Used to determine the exact number of elements. |
| More readable when checking if a list is empty. | Useful when the element count is required. |
Advantages of isEmpty() Method
- Provides a simple way to check whether an ArrayList contains elements.
- Improves code readability compared to checking size() == 0.
- Does not modify the contents of the list.
- Works with ArrayList of primitive wrapper classes, strings, and custom objects.
- Useful for validation before performing list operations.