1. Introduction

Determining the size of an ArrayList is a common operation in Java. The size() method is used to get the number of elements in the list. This method is useful when you need to iterate over the list or perform operations based on the number of elements present. In this post, we will demonstrate how to use the size() method to determine the size of an ArrayList.

2. Program Steps

1. Create an ArrayList.

2. Add some elements to the ArrayList.

3. Use the size() method to get the number of elements in the ArrayList.

4. Print the size of the ArrayList.

3. Code Program

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

public class ArrayListSize {

    public static void main(String[] args) {

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

        // Step 2: Add some elements to the ArrayList
        animalsList.add("Lion");
        animalsList.add("Tiger");
        animalsList.add("Elephant");

        // Step 3: Use the size() method to get the number of elements in the ArrayList
        int sizeOfList = animalsList.size();

        // Step 4: Print the size of the ArrayList
        System.out.println("Size of the ArrayList: " + sizeOfList);
    }
}

Output:

Size of the ArrayList: 3

4. Step By Step Explanation

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

Step 2: We then add three elements, namely "Lion", "Tiger", and "Elephant" to the ArrayList.

Step 3: The size() method is invoked on the ArrayList to determine the number of elements present in it. This method returns the size of the ArrayList as an int.

Step 4: Finally, the size of the ArrayList is printed to the console, which is 3 in this case.