In Java, the array length is the number of elements that an array can holds. There is no predefined method to obtain the length of an array. We can find the array length in Java by using the array attribute length. We use this attribute with the array name. In this section, we will learn how to find the length or size of an array in Java.
Array length Attribute
Java provides an attribute length that determines the length of an array. Every array has an in-built length property whose value is the size of the array. Size implies the total number of elements that an array can contain. The length property can be invoked by using the dot (.) operator followed by the array name. We can find the length of int, double, String, etc. For example:
In the above code snippet, arr is an array of type int that can hold 5 elements. The arrayLength is a variable that stores the length of an array. To find the length of the array, we have used array name (arr) followed by the dot operator and length attribute, respectively. It determines the size of the array.
Note that length determines the maximum number of elements that the array can contain or the capacity of the array. It does not count the elements that are inserted into the array. That is, length returns the total size of the array. For arrays whose elements are initialized at the time of its creation, length and size are the same.
If we talk about the logical size, the index of the array, then simply int arrayLength=arr.length-1, because the array index starts from 0. So, the logical or array index will always be less than the actual size by 1.
A non-negative integer less than 232.Property attributes of
The value of the
The array object observes the
9 values. Empty slots have some special interactions with array methods; see array methods and empty slots.
See also Relationship between
Iterating over an array
In the following example, the array
1 is iterated through by looking at the
Shortening an array
The following example shortens the array
1 to a length of 3 if the current length is greater than 3.
Create empty array of fixed length
Array with non-writable length