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. Show Array length AttributeJava 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. The Try itValueA non-negative integer less than 232. Property attributes ofArray.prototype.length WritableyesEnumerablenoConfigurablenoDescriptionThe value of the
The array object observes the
When 9 values. Empty slots have some special interactions with array methods; see array methods and empty slots.
See also Relationship between ExamplesIterating over an arrayIn the following example, the array 1 is iterated through by looking at the length property. The value in each element is then doubled.
Shortening an arrayThe following example shortens the array 1 to a length of 3 if the current length is greater than 3.
Create empty array of fixed lengthSetting
Array with non-writable lengthThe |