How to use size() to Find Java array size In Java
Alternatively, we can use the size() method of the java.util.ArrayList class, which returns the number of elements in the list.
the Example 1:
Java
// Java program to demonstrate // size() method // for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add( 1 ); arrlist.add( 2 ); arrlist.add( 3 ); arrlist.add( 4 ); arrlist.add( 5 ); // print arrlist System.out.println( "Array: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println( "Size of array = " + size); } } // This code is contributed by Susobhan Akhuli |
Output
Array: [1, 2, 3, 4, 5] Size of array = 5
Example 2:
Java
// Java program to demonstrate // size() method // for String value import java.util.*; public class GFG1 { public static void main(String[] argv) { // Creating object of ArrayList<Integer> ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add( "GFG" ); arrlist.add( "GEEKS" ); arrlist.add( "w3wiki" ); // print arrlist System.out.println( "Array: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println( "Size of array = " + size); } } // This code is contributed by Susobhan Akhuli |
Output
Array: [GFG, GEEKS, w3wiki] Size of array = 3
The complexity of the above method
Time Complexity: O(1)
Auxiliary Space: O(1)
How to find length or size of an Array in Java?
In Java, an array is a data structure that stores a fixed-size collection of elements of the same type. To determine the length or size of an array in Java, we can use different methods.