Arraylist.size(): In the previous article we have discussed about Java ArrayList isempty() Method with Example
In this article we are going to see the use Java ArrayList size() method along with suitable examples.
Java ArrayList size() Method with Example
size():
Size of an arraylist: This java.util.ArrayList.size()
method is used to know the number of elements present in the arraylist.
It returns the size of the ArrayList
Syntax:
arrayListName.size()
Where,
arrayListName
refers to the name of your ArrayList.
Let’s see different examples to understand it more clearly.
Method-1: Java ArrayList size() Method – Example with String Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add string elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Then find the size of the arrayList using
size()
method - Print the size of the ArrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of string datatype ArrayList<String> arr = new ArrayList<String>(); // Adding some elements to the ArrayList arr.add("c"); arr.add("c++"); arr.add("java"); arr.add("python"); arr.add("c#"); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // Prints the size of the ArrayList System.out.println("The size of the ArrayList is: "+arr.size()); } }
Output: The elements of ArrayList are: [c, c++, java, python, c#] The size of the ArrayList is: 5
Method-2: Java ArrayList size() Method – Example with Integer Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add Integer elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Then find the size of the arrayList using
size()
method - Print the size of the ArrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of Integer datatype ArrayList<Integer> arr = new ArrayList<Integer>(); // Adding some elements to the ArrayList arr.add(10); arr.add(20); arr.add(30); arr.add(40); arr.add(50); arr.add(60); arr.add(70); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // Prints the size of the ArrayList System.out.println("The size of the ArrayList is: "+arr.size()); } }
Output: The elements of ArrayList are: [10, 20, 30, 40, 50, 60, 70] The size of the ArrayList is: 7
Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.
Related Java Programs: