1. Introduction

In Java, the ArrayList class provides a method called isEmpty() to check whether the list is empty or not. The isEmpty() method returns a boolean value: true if the list is empty, and false otherwise. This can be particularly useful when performing operations on lists where you need to ensure that the list is not empty. In this blog post, we will go through how to use the isEmpty() method to check if an ArrayList is empty.

2. Program Steps

1. Create an ArrayList.

2. Check if the ArrayList is empty using the isEmpty() method and print the result.

3. Add some elements to the ArrayList.

4. Again, check if the ArrayList is empty using the isEmpty() method and print the result.

3. Code Program

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

public class ArrayListIsEmptyCheck {

    public static void main(String[] args) {

        // Step 1: Create an ArrayList
        List<String> fruitList = new ArrayList<>();

        // Step 2: Check if the ArrayList is empty and print the result
        System.out.println("Is the ArrayList empty? " + fruitList.isEmpty());

        // Step 3: Add some elements to the ArrayList
        fruitList.add("Apple");
        fruitList.add("Banana");

        // Step 4: Again, check if the ArrayList is empty and print the result
        System.out.println("Is the ArrayList empty? " + fruitList.isEmpty());
    }
}

Output:

Is the ArrayList empty? true
Is the ArrayList empty? false

4. Step By Step Explanation

Step 1: We start by creating an empty ArrayList named fruitList.

Step 2: We then use the isEmpty() method to check if the ArrayList is empty. Since fruitList is empty at this point, the method returns true, and the output is: "Is the ArrayList empty? true".

Step 3: Next, we add two elements, "Apple" and "Banana", to the ArrayList.

Step 4: We call the isEmpty() method again to check whether the ArrayList is empty. This time, since fruitList contains elements, the method returns false, and the output is: "Is the ArrayList empty? false".