Array Length
Before you hand out exam papers, you count how many there are. Before a loop walks through an array, it needs the same number: how many elements does the array hold? In Java you ask the array itself, with length. It's one of the first things every loop over an array uses.
length Is a Field
public class Coach {
public static void main(String[] args) {
String[] passengers = {"Navika", "Srihitha", "Advitha"};
System.out.println("Passengers: " + passengers.length);
System.out.println("Last one: " + passengers[passengers.length - 1]);
}
}Passengers: 3
Last one: AdvithaHow it works
- Line 4:
passengers.lengthis 3. There are no brackets:lengthis a field of the array, not a method. - Line 5: the last index is always
length - 1, here 2.
Try it yourself: add a fourth name. Do you need to change line 5?
length vs length() vs size()
| You have | Ask for its size with | Example |
|---|---|---|
| An array | .length (field) | marks.length |
A String | .length() (method) | "Pune".length() → 4 |
A List, Set or Map | .size() (method) | stops.size() |
The difference has a reason: an array's size is fixed when it's created, so it's stored as a simple final value. A String and a collection answer through a method.
Loops Use length
Write loop limits with length instead of a fixed number, so the loop still works when the array changes size:
public class Average {
public static void main(String[] args) {
int[] marks = {78, 92, 86, 64};
int total = 0;
for (int i = 0; i < marks.length; i++) {
total += marks[i];
}
System.out.println("Average: " + (double) total / marks.length);
}
}Average: 80.0i < marks.length (not <=) keeps i between 0 and 3. The (double) cast avoids whole-number division (see "Type Promotion in Expressions").
Empty Arrays
An array can have length 0: int[] none = new int[0]; or {}. That's useful for "no results", and it's safer than null, because loops over it simply do nothing. args in main is an empty array when no command-line arguments are given.
Common Mistakes
Writing marks.length(). Arrays have no length() method: cannot find symbol.
Using <= in the loop. i <= marks.length reaches index length, one past the end.
Trying to change it. marks.length = 10; doesn't compile: cannot assign a value to final variable length.
Interview Corner
Is length a method or a field for arrays?
A field. Arrays use array.length with no brackets, because an array's size is fixed when it's created. String uses the method length(), and collections such as ArrayList use size().
Practice
- Easy: Print the middle element of an array of odd length, using
length / 2. - Harder: Write a loop that prints an array's elements from the last to the first, using only
length(no fixed numbers).
Key Takeaways
Was this tutorial helpful?