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.

Similar Reads

Method 1: Naive Approach to Find Java Array Length

The naive method is used for loop to determine the size/length of char, integer, and string type of arrays....

Method 2: Using length() Method to find Java Array Size

...

Method 3: Using size() to Find Java array size

There is a length field available in the array that can be used to find the length or size of the array....

Method 4: Using Stream API to check Java Array Length

...

Method 5: Using length() method to Check Java Array length

...

Method 6: Using the Collection size() method to find the Java Array size

Alternatively, we can use the size() method of the java.util.ArrayList class, which returns the number of elements in the list....

Method 7: Converting Strings in the List to find the size

...