Home » How to Find Array Length in Java

How to Find Array Length in Java

by Online Tutorials Library

How to Find Array Length in Java

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.

How to Find Array Length in Java

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.

How to Find Array Length in Java

Let’s find the length of the array through an example.

ArrayLengthExample1.java

Output:

The length of the array is: 10  

ArrayLengthExample2.java

Output:

The size of the array is: 7  

ArrayLengthExample3.java

Output:

The array is empty, can't be determined length.  The length of the array is: 6  The length of the array is: 5  The length of the array is: 7  

Next TopicJava Tutorial

You may also like