Size of arraylist – Java Program to Get the Size of ArrayList

Size of arraylist: In the previous article, we have seen Java Program to Change an Element in ArrayList

In this article we are going to see how we can get the size of an arraylist.

Java Program to Get the Size of ArrayList

We have inbuilt size() method in ArrayList which can be used to find the size of arraylist.

Synatx: arrayList_Name.size();

Let’s see the program to understand more clearly.

Java Program to Get the Size of ArrayList By Using size() Method

Approach:

  • Create an arraylist.
  • Add individual elements into the arraylist by using the add( ) library function.
  • Use the size( ) method with the arraylist to find the size.
  • Print the arraylist and its size.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Creating an empty ArrayList
        ArrayList<String> arr = new ArrayList<String>();
        // Adding elements to the arrayList
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        // Displaying the list
        System.out.println("The arraylist is of size "+arr.size()+" and its elements are - "+arr);
    

    }
}

Output:

The arraylist is of size 3 and its elements are - [One, Two, Three]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs: