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.
Know more about arrays, here.
length property
Every array has an in-built length
property whose value is the size of the array. Size implies the total number of elements that the array can contain.
This property is invoked by using dot(.) operator on the name of the array(or variable with which the array is declared) as below
Arrayname.length
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
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.
Hit the clap if the article was worthy.