Getting Array Length with the length Property
What you'll learn: How to find out exactly how many elements an array can hold using the built-in length property.
The Core Idea
Every array in Java has a built-in property called length that tells you how many elements the array can hold. Think of it like checking the number of seats in a movie theater row—you don't need to count them manually; the theater already knows.
Unlike a method that requires parentheses (like methodName()), length is a property—you access it with just a dot and the word length, no parentheses.
Syntax
int[] numbers = {10, 20, 30, 40, 50};
int size = numbers.length; // size is 5
Why This Matters: Avoiding Hard-Coded Bounds
When you learned about ArrayIndexOutOfBoundsException, you saw that accessing invalid indices crashes your program. The length property is your safety tool—it lets you write loops that automatically adapt to any array size:
int[] scores = {95, 87, 92};
// BAD: Hard-coded bound (breaks if array size changes)
for (int i = 0; i < 3; i++) {
System.out.println(scores[i]);
}
// GOOD: Using length property
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
If you later change scores to have 5 elements, the second loop still works perfectly—no code changes needed.
Common Use Cases
- Loop boundaries:
i < array.length - Accessing the last element:
array[array.length - 1] - Checking if an array is empty:
if (array.length == 0)
Key Takeaway: Use the length property instead of hard-coding array sizes—it makes your code flexible, safe, and adaptable to arrays of any size.