The size() method of java.util.ArrayList class is used to get the number of elements in this list.
Syntax:
public int size()
Returns Value: This method returns the number of elements in this list.
Below are the examples to illustrate the size() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<Integer>
arrlist = new ArrayList<Integer>();
arrlist.add( 1 );
arrlist.add( 2 );
arrlist.add( 3 );
arrlist.add( 4 );
arrlist.add( 5 );
System.out.println( "Before operation: "
+ arrlist);
int size = arrlist.size();
System.out.println( "Size of list = "
+ size);
}
catch (IndexOutOfBoundsException e) {
System.out.println( "Exception thrown: "
+ e);
}
}
}
|
Output:
Before operation: [1, 2, 3, 4, 5]
Size of list = 5
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<String>
arrlist = new ArrayList<String>();
arrlist.add( "A" );
arrlist.add( "B" );
arrlist.add( "C" );
System.out.println( "Before operation: "
+ arrlist);
int size = arrlist.size();
System.out.println( "Size of list = "
+ size);
}
catch (IndexOutOfBoundsException e) {
System.out.println( "Exception thrown: "
+ e);
}
}
}
|
Output:
Before operation: [A, B, C]
Size of list = 3
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
26 Nov, 2018
Like Article
Save Article