This post will discuss how to find the length of an array in Java.

There are several methods to find the length of an array in Java, which is the number of elements that an array can hold. Here are some possible ways:

1. Using length property

The standard solution to find the length of an array in Java is using the length property of the array. This is a final variable that is applicable for all types of arrays, such as int[], double[], String[], etc. We can use this property with the array name to get the size of the array. Note that length is a not a method and it is invoked as .length, not as .length().

Download  Run Code

2. Using Reflection

The Array class from the java.lang.reflect package provides several static utility methods to dynamically manipulate arrays in Java. We can find the length of an array using the Array.getLength() method from it. This method can be used to get the length of an array, without knowing their type at compile time. Here is an example of how to use this method:

Download  Run Code

3. Using a List

This is an alternative method where we convert our array to a List and use the size() method of the List interface. We can use the Stream API to convert the primitive array to a List, and then use the size() method to get the number of elements in the list. Here’s an example of how we can achieve this:

Download  Run Code

 
If we have an object array instead of a primitive array, we can directly call the Arrays.asList() method to convert our array to a List. For example:

Download  Run Code

4. Using Guava library

Another approach to find the length of an array is to use the Ints.asList() method from the com.google.common.collect package to create a fixed-size list that is backed by the specified array, and then call its size() method to get the number of elements in the list. Here is an example of how to use these method:

Download Code

5. Using a loop

Finally, we can use a loop to iterate over the elements of the array and count them. This is a naive method that can be used for any type of array, but it requires more time and space than using the length property. We can use a for loop or a for-each loop to traverse the array and increment a counter variable for each element. For example:

Download  Run Code

That’s all about finding the length of an array in Java.