Write a Java Program to find number of elements in ArrayList


This Java program demonstrates how to find the size of an ArrayList, add elements to it, and clear the elements. Here's how the code works:

  • An ArrayList named fru_list of type String is created.
  • The size() method is used to find the size of the ArrayList, which is 0 because the ArrayList is empty.
  • Several strings are added to the ArrayList using the add() method.
  • The size() method is called again to find the new size of the ArrayList after adding the elements.
  • The clear() method is used to remove all the elements from the ArrayList.
  • The size() method is called again to find the new size of the ArrayList after clearing the elements.
  • The output shows the initial size of the ArrayList, the new size of the ArrayList after adding elements, and the size of the ArrayList after clearing the elements.

Note that the size() method returns the number of elements in the ArrayList, which is an integer.

Source Code

import java.util.ArrayList;
public class NumElement_ArrayList
{
	public static void main(String[] args)
	{
		ArrayList<String> fru_list = new ArrayList<>();
		int s = fru_list.size();
		System.out.println("After Creating Size of Array List : " + s);
 
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		fru_list.add("Mango");
		fru_list.add("Pineapple");
		s = fru_list.size();
 
		System.out.println("Length of ArrayList After Adding Elements : " + s);
 
		fru_list.clear();
		s = fru_list.size();
		System.out.println("Size of ArrayList After Clearing Elements : " + s);
	}
}

Output

After Creating Size of Array List : 0
Length of ArrayList After Adding Elements : 8
Size of ArrayList After Clearing Elements : 0

Example Programs