CKTIS / Java
array.length — array length
The expression array.length reads the number of array elements as an int. length is a public final field, not a method: the syntax has no parentheses, and an existing array's length cannot be changed.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
array.lengtharray.length reads the int field length, which gives the number of array elements. The field is public final: you cannot assign it a new value. Use array.length, not array.length().
The length may be 0. Valid indices satisfy 0 <= i && i < array.length, so use <, not <=, in a loop. Length counts every slot, including those containing default values.
If array is null, reading array.length throws NullPointerException instead of returning 0. Check the reference before reading if it might be null.
For a multidimensional array, array.length describes only the outer array. Each inner array has its own length and may contain a different number of elements.
Examples
public class Main {
public static void main(String[] args) {
int[] array = {4, 0, 9};
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println(array.length);
System.out.println(sum);
System.out.println(new int[0].length);
}
}Result
3 13 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.