Length of array means the total number of elements that an array can hold.
Array can be an integer array, a double array, a String array or an array of objects.
Method to  find the size of array remains the same for all types of array.

1. length property

A java array has an inbuilt length property, which gives the total elements of array. Example,

class ArrayLengthFinder {
   public static void main(String[] arr) {
      // declare an array
      int[] array = new int[10];
      array[0] = 12;
      array[1] = -4;
      array[2] = 1;
      // get the length of array 
      int length = array.length;
      System.out.println("Length of array is: " + length);
   }
}

Above code declares an array and assigns values to its 3 elements. It then calculates the size of array using length property and prints it.
Output will be

Length of array is: 10

2. Iterating an array

Another method to find the length of an array is by looping over the array with an enhanced for loop and counting the number of iterations as shown below

class ArrayLengthFinder {
   public static void main(String[] arr) {
    // declare an array
    int[] array = {12, -4, 1};
    int length = 0;
    for(int element: array) {
      length++;
    }
    System.out.println("Length of array is: " + length); // 3
   }
}

3. Java 8 stream

Java 8 stream provides a count method which returns the total elements in the stream.

To convert a java array to a stream, use static stream() method of Arrays class. Example,

class ArrayLengthFinder {
   public static void main(String[] arr) {
    // declare an array
    int[] array = {12, -4, 1};
    int length = Arrays.stream().count();
    System.out.println("Length of array is: " + length); // 3
   }
}

length vs size
Note that length determines the maximum number of elements that the array can contain or the capacity of the array and not the count of elements that are inserted into the array.
That is, length returns the total size of array.
Thus, in the above example, only 3 elements are inserted into the array while length returns 10.
For arrays whose elements are initialized at the time of its creation, length and size are the same. Example,

class ArrayLengthFinder {
   public static void main(String[] arr) {
      // declare and initialize an array
      String[] array = {"BMW", "Audi", "Mercedes"};
      // get the length of array 
      int length = array.length;
      System.out.println("Length of array is: " + length);
   }
}

It prints

Length of array is: 3

In the above example, total number of elements in the array is 3 and length property also returns 3.

Leave a Reply