Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

array.length

The length of an array — the number of elements. A field, not a method: no parentheses.

Available since: Java 1.0

Syntax

public final int length

Examples

The length and the last element:

void main() {
    int[] numbers = {4, 8, 15, 16, 23, 42};
    IO.println(numbers.length);
    IO.println(numbers[numbers.length - 1]);
}

Output:

6
42

A loop over indexes, and going out of bounds:

void main() {
    String[] names = new String[3];
    names[0] = "Anna";
    for (int i = 0; i < names.length; i++) {
        IO.println(i + ": " + names[i]);
    }
    try {
        names[3] = "Oleg";
    } catch (ArrayIndexOutOfBoundsException e) {
        IO.println(e.getMessage());
    }
}

Output:

0: Anna
1: null
2: null
Index 3 out of bounds for length 3

Notes

The size of an array is fixed when it is created. New arrays are filled with default values: 0 for numbers, false for boolean, null for objects. Indexes go from 0 to length - 1. If you need a list that grows, use ArrayList.

Do not mix them up: arrays have length, strings length(), collections size().

See also

  • Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
  • for — A loop with a counter, or iteration over every element of an array or collection (for-each).
  • String.length() — Returns the number of characters in a string.

In the tutorial

  • Arrays — Arrays in Java: creating them, index access, length, default values, looping over them and printing with Arrays.toString.

Thanks for reading!

Donate to the site — we work hard for you.