Java Utility Library

Java ArrayList - size() Method



The java.util.ArrayList.size() method returns the number of elements in the ArrayList.

Syntax

public int size()

Parameters

No parameter is required.

Return Value

Returns the number of elements in the ArrayList.

Exception

NA

Example:

In the example below, the java.util.ArrayList.size() method is used to find out the number of elements in the ArrayList.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    System.out.println("Size of MyList: " + MyList.size());    

    //adding one more element in the ArrayList
    MyList.add(40);
    System.out.println("One element is added in the MyList."); 

    System.out.println("Now, Size of MyList: " + MyList.size());  
  }
}

The output of the above code will be:

Size of MyList: 3
One element is added in the MyList.
Now, Size of MyList: 4

❮ Java.util - ArrayList