Java Basic Examples

Java array length example

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

How to get array length in Java?

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

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



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 array is empty?

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



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


How to iterate array using array length?

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


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

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.