List size() method in Java with Examples

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

Before operation: [1, 2, 3, 4, 5]
Size of list = 5

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

Before operation: [A, B, C]
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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.