Check if ArrayList is empty or not in Java

Learn to check if ArrayList is empty or not using isEmpty() and size() methods. Please note that isEmpty() method also internally check the size of arraylist.

1. Check if ArrayList is empty – isEmpty() example

ArrayList isEmpty() method returns true if list contains no element. In other words, method returns true if list is empty. Else isEmpty() method returns false.

In given example, we have first initialized a blank arraylist and checked if it is empty. Method returns true because there is nothing in the list. Then we added an element "A" to list and checked again. This time list is not empty and method returns false. Now we again cleared the list and checked again. List is empty again.

In application programming, it is advisable to check both if list is not null and then not empty. If list is not initialized, you may get NullPointerException in runtime.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>();
        
        System.out.println(list.isEmpty());     //true
        
        list.add("A");
        
        System.out.println(list.isEmpty());     //false
        
        list.clear();
        
        System.out.println(list.isEmpty());     //true
    }
}

Program output.

true
false
true

2. Check if ArrayList is empty – size() example

Another way to check if arraylist contains any element or not, we can check the size of arraylist. If the list size is greater than zero, then list is not empty. If list size is 0, list is empty.

If we look inside the isEmpty() method, it also check the size of arraylist to determine if the list is empty or not.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>();
        
        System.out.println(list.size());     //0
        
        list.add("A");
        
        System.out.println(list.size());     //1
        
        list.clear();
        
        System.out.println(list.size() == 0);     //true
    }
}

Program output.

0
1
true

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Check if ArrayList is empty or not in Java”

  1. Don’t use size() to check whether the list is empty or not. Use isEmpty() instead — unless you like to reinvent the wheel.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.