ArrayList size() method in java

Let’s learn ArrayList size() method in java.

ArrayList size() method in java

size() method of ArrayList class returns the number of elements in this list.

Syntax:

public int size()

Returns:

the number of elements in this list.

Also read – ArrayList in java

Now let’s see example on ArrayList size() method.

import java.util.ArrayList;
public class ArrayListSizeMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      int s = al.size();
      System.out.println("size of ArrayList: " + s);
      al.add("red");
      al.add("blue");
      al.add("green");
      s = al.size();
      System.out.println("size of ArrayList after adding elements: " + s);
      al.clear();
      s = al.size();
      System.out.println("size of ArrayList after clearing elements: " + s);
   }
}


Output:

size of ArrayList: 0
size of ArrayList after adding elements: 3
size of ArrayList after clearing elements: 0


Let’s see another example.

import java.util.ArrayList;
public class ArrayListSizeMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      int s = al.size();
      System.out.println("size of ArrayList: " + s);
      al.add(25);
      al.add(64);
      al.add(73);
      s = al.size();
      System.out.println("size of ArrayList after adding elements: " + s);
      al.clear();
      s = al.size();
      System.out.println("size of ArrayList after clearing elements: " + s);
   }
}


Output:

size of ArrayList: 0
size of ArrayList after adding elements: 3
size of ArrayList after clearing elements: 0