How to Check If a List Is Empty in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively check if a list in Java is empty. We will explore the standard isEmpty() method, verify list size using size(), and understand how to handle potential null list scenarios to write robust and reliable code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("ArrayList") subgraph Lab Skills java/arrays_methods -.-> lab-559949{{"How to Check If a List Is Empty in Java"}} java/collections_methods -.-> lab-559949{{"How to Check If a List Is Empty in Java"}} java/exceptions -.-> lab-559949{{"How to Check If a List Is Empty in Java"}} java/arraylist -.-> lab-559949{{"How to Check If a List Is Empty in Java"}} end

Use isEmpty() for List Check

In this step, we will learn how to check if a list in Java is empty using the isEmpty() method. This is a common task in programming, and isEmpty() provides a clear and efficient way to do it.

First, let's create a new Java file named ListCheck.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing ListCheck.java.

Now, open ListCheck.java in the editor and add the following code:

import java.util.ArrayList;
import java.util.List;

public class ListCheck {

    public static void main(String[] args) {
        // Create an empty list
        List<String> emptyList = new ArrayList<>();

        // Create a list with elements
        List<String> populatedList = new ArrayList<>();
        populatedList.add("Apple");
        populatedList.add("Banana");

        // Check if the lists are empty using isEmpty()
        System.out.println("Is emptyList empty? " + emptyList.isEmpty());
        System.out.println("Is populatedList empty? " + populatedList.isEmpty());
    }
}

Let's break down this code:

  • import java.util.ArrayList; and import java.util.List;: These lines import the necessary classes to work with lists.
  • List<String> emptyList = new ArrayList<>();: This line creates a new empty list that can hold String objects.
  • List<String> populatedList = new ArrayList<>();: This line creates another new list.
  • populatedList.add("Apple"); and populatedList.add("Banana");: These lines add elements to the populatedList.
  • System.out.println("Is emptyList empty? " + emptyList.isEmpty());: This line calls the isEmpty() method on emptyList. The isEmpty() method returns true if the list has no elements and false otherwise. The result is then printed to the console.
  • System.out.println("Is populatedList empty? " + populatedList.isEmpty());: This line does the same for populatedList.

Save the ListCheck.java file.

Now, open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. You can use the command cd ~/project if needed.

Compile the Java code using the javac command:

javac ListCheck.java

If there are no errors, a ListCheck.class file will be created in the ~/project directory.

Finally, run the compiled Java program using the java command:

java ListCheck

You should see output similar to this:

Is emptyList empty? true
Is populatedList empty? false

This output confirms that isEmpty() correctly identified the empty list and the list with elements. Using isEmpty() is the preferred way to check for an empty list in Java as it is more readable and potentially more efficient than checking the size.

Verify List Size with size()

In the previous step, we learned how to check if a list is empty using isEmpty(). While isEmpty() is great for checking if a list has any elements, sometimes you need to know exactly how many elements are in a list. For this, Java provides the size() method.

In this step, we will modify our ListCheck.java file to use the size() method and see how it works.

Open the ListCheck.java file in the WebIDE editor if it's not already open. It should be located in your ~/project directory.

Now, let's add some lines to our main method to print the size of our lists. Add the following lines after the lines where you used isEmpty():

import java.util.ArrayList;
import java.util.List;

public class ListCheck {

    public static void main(String[] args) {
        // Create an empty list
        List<String> emptyList = new ArrayList<>();

        // Create a list with elements
        List<String> populatedList = new ArrayList<>();
        populatedList.add("Apple");
        populatedList.add("Banana");

        // Check if the lists are empty using isEmpty()
        System.out.println("Is emptyList empty? " + emptyList.isEmpty());
        System.out.println("Is populatedList empty? " + populatedList.isEmpty());

        // Get and print the size of the lists using size()
        System.out.println("Size of emptyList: " + emptyList.size());
        System.out.println("Size of populatedList: " + populatedList.size());
    }
}

We added two new lines:

  • System.out.println("Size of emptyList: " + emptyList.size());: This line calls the size() method on emptyList. The size() method returns the number of elements in the list as an integer.
  • System.out.println("Size of populatedList: " + populatedList.size());: This line does the same for populatedList.

Save the ListCheck.java file.

Now, go back to the Terminal in the ~/project directory. We need to recompile the modified Java code:

javac ListCheck.java

If the compilation is successful, run the program again:

java ListCheck

You should now see output similar to this:

Is emptyList empty? true
Is populatedList empty? false
Size of emptyList: 0
Size of populatedList: 2

As you can see, size() correctly reported that emptyList has 0 elements and populatedList has 2 elements.

While you could check if a list is empty by checking if its size is 0 (list.size() == 0), using isEmpty() is generally preferred for clarity and readability. However, size() is essential when you need to know the exact number of elements in a list, for example, when looping through the list or performing calculations based on the number of items.

Handle Null Lists

In the previous steps, we worked with lists that were either empty or contained elements. However, in real-world programming, it's possible for a list variable to be null. A null reference means the variable doesn't point to any object in memory. Trying to call a method like isEmpty() or size() on a null list will result in a NullPointerException, which is a common error in Java.

In this step, we will learn how to safely handle null lists before attempting to check if they are empty or get their size.

Open the ListCheck.java file in the WebIDE editor.

Let's add a new list variable and set it to null. Then, we'll demonstrate what happens when you try to call methods on it without checking for null. Modify your main method to include the following code:

import java.util.ArrayList;
import java.util.List;

public class ListCheck {

    public static void main(String[] args) {
        // Create an empty list
        List<String> emptyList = new ArrayList<>();

        // Create a list with elements
        List<String> populatedList = new ArrayList<>();
        populatedList.add("Apple");
        populatedList.add("Banana");

        // Create a null list
        List<String> nullList = null;

        // Check if the lists are empty using isEmpty()
        System.out.println("Is emptyList empty? " + emptyList.isEmpty());
        System.out.println("Is populatedList empty? " + populatedList.isEmpty());

        // Get and print the size of the lists using size()
        System.out.println("Size of emptyList: " + emptyList.size());
        System.out.println("Size of populatedList: " + populatedList.size());

        // --- This part will cause an error if uncommented ---
        // System.out.println("Is nullList empty? " + nullList.isEmpty()); // This line will cause a NullPointerException
        // System.out.println("Size of nullList: " + nullList.size());   // This line will also cause a NullPointerException
        // ----------------------------------------------------

        // Safely check for null before calling methods
        System.out.println("\nSafely checking for null:");
        if (nullList == null) {
            System.out.println("nullList is null.");
        } else {
            System.out.println("Is nullList empty? " + nullList.isEmpty());
            System.out.println("Size of nullList: " + nullList.size());
        }

        if (emptyList == null) {
             System.out.println("emptyList is null.");
        } else {
             System.out.println("Is emptyList empty? " + emptyList.isEmpty());
             System.out.println("Size of emptyList: " + emptyList.size());
        }
    }
}

We added:

  • List<String> nullList = null;: This declares a list variable but sets its value to null.
  • Commented out lines that would cause a NullPointerException.
  • An if statement: if (nullList == null). This is the crucial part for handling null. We check if the nullList variable is null before trying to call any methods on it. If it is null, we print a message. If it's not null, we can safely call isEmpty() and size().
  • We also added a similar check for emptyList to show that the if condition works correctly for non-null lists as well.

Save the ListCheck.java file.

Compile the modified code in the Terminal:

javac ListCheck.java

Run the program:

java ListCheck

The output should look like this:

Is emptyList empty? true
Is populatedList empty? false
Size of emptyList: 0
Size of populatedList: 2

Safely checking for null:
nullList is null.
Is emptyList empty? true
Size of emptyList: 0

Notice that we successfully checked if nullList was null and avoided the NullPointerException. We also confirmed that the check works correctly for emptyList.

Always remember to check if a list (or any object reference) might be null before calling methods on it. This is a fundamental practice in Java to prevent NullPointerException errors. A common pattern is if (myList != null && !myList.isEmpty()) to check if a list is not null and not empty in one condition.

Summary

In this lab, we learned how to check if a list in Java is empty. We started by exploring the isEmpty() method, which provides a straightforward and efficient way to determine if a list contains any elements. We created example lists, both empty and populated, and used isEmpty() to verify their state, observing the boolean output.

We also examined how to use the size() method to check if a list is empty by comparing its size to zero. This method returns the number of elements in the list, and a size of 0 indicates an empty list. Finally, we addressed the crucial aspect of handling null lists before attempting to check for emptiness, demonstrating how to prevent NullPointerException by adding a null check.