![]() |
VOOZH | about |
Finding the length of an array is a very common and basic task in Java programming. Knowing the size of an array is essential so that we can perform certain operations. In this article, we will discuss multiple ways to find the length or size of an array in Java.
In this article, we will learn:
The length property is the most common way to find the size of an array in Java. It gives the exact number of elements present in the array.
Example: This example demonstrates how to find the length (size) of an array using the length property.
The size of the Array is 4
Time complexity: O(1) constant time
Note:
When iterating over an array, we can also determine its size manually.
Example: This example, demonstrates how to use for each loop to calculate the length of an array.
The Size of the array is 7
Time Complexity: O(n) slower than length
Note: This approach is not recommended in real world code.
Stream API was introduced in Java 8 and because of it we can perform various operations on arrays using functional programming. The Stream class provide count() method which is used to count the number of elements in an array.
Example: This example, demonstrates using Arrays.stream() with count() to calculate the length of an array.
The size of the array is 5
Time Complexity: O(n)
Note: Avoid Arrays.stream(arr).count() for arrays because it forces unnecessary iteration.
The difference between length, length() and size() is listed below:
Feature | Used For | Example |
|---|---|---|
length | It is used for arrays to calculate the number of elements | arr.length |
length() | It is used for strings to calculate the number of characters in the string | s.length() |
size() | It is used for collections like ArrayList or List to calculate the number of elements | list.size() |