Check if an ArrayList is Empty in Java

To check if an ArrayList is empty, you can use ArrayList.isEmpty() method or first check if the ArrayList is null, and if not null, check its size using ArrayList.size() method. The size of an empty ArrayList is zero.

ArrayList.isEmpty() – Reference to Syntax and Examples of isEmpty() method.

ArrayList.size() – Reference to Syntax and Examples of size() method.

Example 1 – Check if ArrayList is Empty using ArrayList.isEmpty()

ArrayList.isEmpty() method returns true if the ArrayList is empty, and false if it is not empty.

In the following example, we will create an ArrayList, add no elements to it, and check if it is empty or not by using ArrayList.isEmpty() method.

Java Program

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<String> myList = new ArrayList<String>();
		
		if(myList.isEmpty()) {
			System.out.println("ArrayList is empty.");
		} else {
			System.out.println("ArrayList is not empty.");
		}
	}
}

Output

ArrayList is empty.
ADVERTISEMENT

Example 2 – Check if ArrayList is Empty using Size

In the following example, we will create an ArrayList, add no elements to it, and check if it is empty or not by getting the size of the ArrayList.

Java Program

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<String> myList = new ArrayList<String>();
		
		if(myList==null || myList.size()==0) {
			System.out.println("ArrayList is empty.");
		} else {
			System.out.println("ArrayList is not empty.");
		}
	}
}

Output

ArrayList is empty.

Conclusion

In this Java Tutorial, we learned how to check if an ArrayList is empty or not using ArrayList built-in methods.