Array Length

Naveen AnamaneniUpdated · 3 min read

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

Coach.java▶ Try it
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]);
    }
}
Output
Passengers: 3
Last one: Advitha

How it works

  1. Line 4: passengers.length is 3. There are no brackets: length is a field of the array, not a method.
  2. 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 haveAsk for its size withExample
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:

Average.java▶ Try it
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);
    }
}
Output
Average: 80.0

i < 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

  1. Easy: Print the middle element of an array of odd length, using length / 2.
  2. Harder: Write a loop that prints an array's elements from the last to the first, using only length (no fixed numbers).

Quick check: Array length

4 questions
1How do you get the number of elements in int[] a?
2What is the last valid index of an array with length 5?
3Which gives the length of the String "Pune"?
4What is new int[0].length?

Key Takeaways

Was this tutorial helpful?

Lesson 69 of 482