Skip to content

Java array length example

Java array length example shows how to find array length in Java. The example also shows how to access array elements using the array length property.

How to get array length in Java?

Arrays in Java are objects that can be created dynamically and hold a set of elements of the same type. Java array does not have any method that returns the size of an array, but instead array length is available as a final instance property named length.

In order to get the array length, we need to access its length property.

Example

Output

Array length can be 0 or any positive number equal to the number of elements in the array.

How to use array length to check if the array is empty?

You can use the array length property to check if the array is empty. If the length of the array is 0, the array is empty, otherwise not.

Example

Output

Instead of if-else, you can also use Java ternary operator to check if the array is empty using the array length property as given below.

Output

How to iterate array using array length?

If you want to iterate through elements of an array, you can use the array length property along with the for loop as given in the below example.

Output

Remember that the index of the Java array starts from 0. That means that the first element of an array is located at index 0 and goes up to an array size – 1 index. That is why we started the for loop at 0 the index and went up to array.length – 1 index.

This example is a part of the Java Array tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.