Skip to content
Related Articles

Related Articles

Improve Article
List size() method in Java with Examples
  • Last Updated : 16 Oct, 2020

The size() method of List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.
Syntax: 
 

public int size()

Parameters: This method does not takes any parameters.
Return Value: This method returns the number of elements in this list.
Below are the examples to illustrate the size() method. 
Example 1: 
 

Java




// Java program to demonstrate
// size() method for Integer value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] arg)
    {
        // Creating object of ArrayList<Integer>
        List<Integer> list = new ArrayList<Integer>();
 
        // Populating List
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
 
        // print List
        System.out.println("Before operation: "
                           + list);
 
        // getting total size of list
        // using size() method
        int size = list.size();
 
        // print the size of list
        System.out.println("Size of list = "
                           + size);
    }
}
Output
Before operation: [1, 2, 3, 4, 5]
Size of list = 5


Example 2: 
 

Java




// Java program to demonstrate
// size() method for String value
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] args)
    {
 
        // Creating object of List<Integer>
        List<String> list = new ArrayList<String>();
 
        // Populating List
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
 
        // print list
        System.out.println("Before operation: "
                           + list);
 
        // getting total size of list
        // using size() method
        int size = list.size();
 
        // print the size of list
        System.out.println("Size of list = "
                           + size);
    }
}
Output
Before operation: [Geeks, for, Geeks]
Size of list = 3


Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#size()
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :