Length of Arrays
The length of an array in Java is the number of elements it holds. It is stored in a special length field that every array has: array.length. The length is set once, when the array is created, and never changes after that. In this lesson you will learn how to get the length of one-dimensional, multidimensional, and jagged arrays, how length differs from the length() method of strings and size() of collections, and which small details trip up beginners most often.
The length Field: How to Get an Array's Length
An array in Java is an object, and that object has a public read-only field called length. You access it with a dot, just like any other field:
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length); // 4 Notice that there are no parentheses after length. It is not a method — it is a field (often informally called the length property) that the JVM fills in at the moment the array is created.
Important
For arrays, length is a field (no parentheses); for strings, length() is a method (with parentheses). Writing array.length() will not compile, and neither will str.length without parentheses. This mix-up is one of the most frequent beginner mistakes and a popular interview question.
The length of an array is fixed at creation time and cannot be changed. If you need to "grow" an array, you have to create a new, larger array and copy the elements into it (for example, with Arrays.copyOf) — or use an ArrayList from the start, which resizes automatically.
Length of a One-Dimensional Array
With a one-dimensional array everything is straightforward: its length is the total number of elements. Keep in mind that element indexes run from 0 to length - 1, so the last element is array[array.length - 1], not array[array.length]:
public class ArrayLengthExample {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4};
System.out.println("Length of array1 = " + array1.length);
System.out.println("First element = " + array1[0]);
System.out.println("Last element = " + array1[array1.length - 1]);
}
} Output:
Length of array1 = 4
First element = 1
Last element = 4 The length field is used all the time in loops that iterate over an array:
int[] array1 = {1, 2, 3, 4};
for (int i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
} The loop condition must be strictly i < array1.length. If you write i <= array1.length, the last iteration will access an index that does not exist and throw an exception:
int[] array1 = {1, 2, 3, 4};
// Error: index 4 does not exist; valid indexes are 0..3
System.out.println(array1[array1.length]);
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
// Index 4 out of bounds for length 4 Length of Multidimensional and Jagged Arrays
A two-dimensional array in Java is really an "array of arrays". That is why array2.length returns the number of rows (the length of the first dimension), while array2[i].length returns the number of elements in the row at index i:
public class MultiArrayLengthExample {
public static void main(String[] args) {
int[][] array2 = {{1, 1, 1}, {2, 2, 2}};
System.out.println("Number of rows in array2 = " + array2.length);
System.out.println("Length of row at index 0 = " + array2[0].length);
System.out.println("Length of row at index 1 = " + array2[1].length);
}
} Output:
Number of rows in array2 = 2
Length of row at index 0 = 3
Length of row at index 1 = 3 In Java, the rows of a two-dimensional array may have different lengths — such arrays are called jagged (or ragged) arrays. So you cannot assume that every row is as long as the first one: each row has to be asked for its own length.
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jagged = {
{1},
{2, 3, 4},
{5, 6}
};
for (int i = 0; i < jagged.length; i++) {
System.out.println("Row " + i + ", length = "
+ jagged[i].length);
}
}
} Output:
Row 0, length = 1
Row 1, length = 3
Row 2, length = 2 The total number of elements in a jagged array has to be computed manually — by summing the lengths of all rows:
int total = 0;
for (int[] row : jagged) {
total += row.length;
}
System.out.println("Total elements: " + total); // Total elements: 6 Empty Array vs null
An empty array is a real object with zero length: reading its length field returns 0. But if the array reference is null, there is no array object at all, and any attempt to read length ends with a NullPointerException:
int[] empty = new int[0];
System.out.println(empty.length); // 0 — perfectly fine
int[] nothing = null;
System.out.println(nothing.length); // NullPointerException! Tip
If an array comes from outside (a method parameter, a result of someone else's code), check the reference for null first and only then read length: if (array != null && array.length > 0) { ... }. The order of the conditions matters — thanks to short-circuit evaluation of &&, the second check is skipped for a null reference.
length, length(), and size(): What's the Difference
In Java, different data types expose their "length" in different ways, and these three variants are constantly confused:
| Syntax | What it is | Where it is used | Example |
|---|---|---|---|
length | Field (no parentheses) | Arrays | array.length |
length() | Method | Strings (String, StringBuilder) | str.length() |
size() | Method | Collections (List, Set, Map) | list.size() |
Here is a short example where all three appear at once:
import java.util.List;
public class LengthVsSizeExample {
public static void main(String[] args) {
int[] array = {1, 2, 3};
String text = "Java";
List<String> list = List.of("a", "b");
System.out.println(array.length); // 3 — array field
System.out.println(text.length()); // 4 — String method
System.out.println(list.size()); // 2 — collection method
}
} Where Developers Get Tripped Up
A few typical slip-ups when working with array length:
array.length()with parentheses. Does not compile: for arrays,lengthis a field. Parentheses belong to strings only:str.length().- Accessing index
array.length. The last valid index isarray.length - 1. Accessingarray[array.length]throws anArrayIndexOutOfBoundsException. - The loop condition
i <= array.length. The classic off-by-one error: the loop performs one extra iteration and crashes with an exception. Correct:i < array.length. - Assuming all rows of a 2D array have the same length. In a jagged array they do not — get each row's length via
array[i].length. - Reading
lengthon a null reference. Results in aNullPointerException. An empty array (length == 0) andnullare fundamentally different things. - Trying to assign a new value to
length. The codearray.length = 10;does not compile: the field is final, and an array's size cannot be changed.
Best Practices
- For a simple pass over all elements, use the
for-eachloop — it never toucheslengthat all, so you cannot get the bounds wrong:for (int x : array) { ... }. - The last element of an array is always
array[array.length - 1]; make writing this expression a habit. - If the amount of data is unknown in advance or has to change, use an
ArrayListinstead of an array: itssize()method always returns the current number of elements. - Prefer returning an empty array (
new int[0]) from methods rather thannull— the calling code will not need an extra null check. - To "resize" an array, use
Arrays.copyOf(array, newLength)— it creates a new array of the required length and copies the elements over.
Frequently Asked Questions
Why is length a field for arrays but a method length() for String?
It is a historical design decision: arrays are built into the language at the JVM level, and their length is stored directly in the object header as a ready-made value, so it is exposed as a field. String is a regular class, and its length is encapsulated behind the length() method, as is customary in object-oriented design.
Can you change the length of an array after it is created?
No. An array's length is fixed forever at creation time, and the length field is read-only. To get an array of a different size, create a new one and copy the elements — the easiest way is Arrays.copyOf(array, newLength). If the size needs to change often, use an ArrayList instead.
What does length return for an empty array or a null reference?
For an empty array (new int[0]) the length field returns zero — it is a valid object of zero length. If the reference is null, no array object exists, and reading length throws a NullPointerException. That is why arrays received from external code are first checked for null and only then asked for their length.
How do you get the total number of elements in a 2D array?
array.length only gives you the number of rows. To get the total element count, sum the lengths of all rows in a loop: for (int[] row : array) total += row.length. For a rectangular array you can multiply array.length by array[0].length, but for a jagged array that produces a wrong result.
Comments