In this tutorial, we will learn about the Java ArrayList isEmpty() method, and learn how to use this method to check if this ArrayList is empty or not, with the help of examples.

Java ArrayList isEmpty() method

ArrayList isEmpty() Returns true if this list contains no elements.

Syntax

The syntax of isEmpty() method is

ArrayList.isEmpty()

Returns

The method returns boolean value.

ADVERTISEMENT

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

In this example, we will take an empty ArrayList of strings and check programmatically if this ArrayList is empty or not using ArrayList.isEmpty() method.

Java Program

import java.util.ArrayList;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();
		boolean result = arrayList.isEmpty();
		System.out.println("Is the ArrayList empty? " + result);
    }  
}

Output

Is the ArrayList empty? true

2. isEmpty() – ArrayList is not empty

In this example, we will define an ArrayList and add an element to it. Now this ArrayList is not empty. So, a call to isEmpty() method on this ArrayList should return false.

Java Program

import java.util.ArrayList;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("a");
		boolean result = arrayList.isEmpty();
		System.out.println("Is the ArrayList empty? " + result);
    }  
}

Output

Is the ArrayList empty? false

3. isEmpty() – Null ArrayList

In this example, we will take a null ArrayList and try to call isEmpty on this ArrayList. Since ArrayList is null, isEmpty() throws java.lang.NullPointerException.

Java Program

import java.util.ArrayList;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = null;
		boolean result = arrayList.isEmpty();
    }  
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:6)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList isEmpty() method, and also learnt how to use this method with the help of Java example programs.