How to Find Length of Array in Java: Simple Guide
In Java, you find the length of an array using the
array.length property. This returns the number of elements in the array as an integer.Syntax
To get the length of an array, use the array.length property. Here, array is the name of your array variable.
- array: your array variable
- length: a property that holds the size of the array
java
int length = array.length;Example
This example creates an array of integers and prints its length using array.length.
java
public class ArrayLengthExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Length of array: " + numbers.length); } }
Output
Length of array: 5
Common Pitfalls
One common mistake is trying to use array.length() as if it were a method. In Java, length is a property, not a method, so it has no parentheses.
Also, length works only for arrays, not for collections like ArrayList. For collections, use size() method instead.
java
public class CommonPitfalls { public static void main(String[] args) { int[] arr = {1, 2, 3}; // Wrong: arr.length() - this causes a compile error // Correct: int len = arr.length; System.out.println("Array length: " + len); } }
Output
Array length: 3
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Array length | array.length | Property, no parentheses |
| ArrayList size | arrayList.size() | Method, requires parentheses |
| String length | string.length() | Method, requires parentheses |
Key Takeaways
Use
array.length to get the size of an array in Java.length is a property, not a method, so do not use parentheses.For collections like
ArrayList, use size() method instead.Remember that
length works only with arrays, not with strings or collections.Always check the type of your data structure to use the correct way to get its size.