Array length
Every Java array carries one built-in piece of information you’ll use in almost every program: its length. Understanding exactly what length tells you — and what it doesn’t — saves you from off-by-one errors and ArrayIndexOutOfBoundsException headaches.
What Is length?
length is a final instance field on every Java array object. It stores the number of elements the array was created to hold. You access it with dot notation, just like a field on any other object.
int[] numbers = new int[5];
System.out.println(numbers.length); // 5
String[] names = {"Alice", "Bob", "Charlie"};
System.out.println(names.length); // 3
Output:
5
3
A few important facts about length:
- It reflects the capacity of the array, not how many elements you’ve actually assigned a meaningful value to.
- It is read-only — you cannot write
numbers.length = 10. The compiler rejects it. - It is set once at array creation and never changes. Java arrays have a fixed size.
Note:
lengthis a field, not a method. There are no parentheses —array.length, notarray.length(). Strings, by contrast, usestr.length()(a method). This distinction trips up nearly every beginner at least once.
Using length in Loops
The most common use of length is as the upper bound in a for loop. Because arrays are zero-indexed, valid indices run from 0 to length - 1.
int[] scores = {88, 92, 75, 100, 67};
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + ": " + scores[i]);
}
Output:
Score 0: 88
Score 1: 92
Score 2: 75
Score 3: 100
Score 4: 67
Using scores.length instead of a hard-coded 5 means your loop automatically adapts if the array size changes — a key habit for maintainable code.
Tip: When you only need the values and not the index, the for-each loop is even simpler:
for (int s : scores) { ... }. It handles bounds internally.
Common Off-by-One Mistake
// WRONG — throws ArrayIndexOutOfBoundsException on the last iteration
for (int i = 0; i <= scores.length; i++) {
System.out.println(scores[i]);
}
// CORRECT
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
The valid last index is length - 1, so use < not <=.
length With an Empty Array
An array can be created with zero elements. Its length is 0, and iterating over it simply executes the loop body zero times — no exception.
int[] empty = new int[0];
System.out.println(empty.length); // 0
for (int val : empty) {
System.out.println(val); // never executes
}
System.out.println("Loop finished safely.");
Output:
0
Loop finished safely.
This pattern is useful in APIs that return an array: returning new int[0] instead of null lets callers loop over the result safely without a null check.
Tip: Prefer returning an empty array over
nullfrom methods. It eliminates an entire class ofNullPointerExceptionbugs in calling code.
length With Multidimensional Arrays
For multidimensional arrays, length only gives you the size of the outermost dimension. To get the size of an inner dimension, you index into the outer array first.
int[][] grid = new int[3][4]; // 3 rows, 4 columns
System.out.println(grid.length); // 3 (number of rows)
System.out.println(grid[0].length); // 4 (number of columns in row 0)
Output:
3
4
To iterate over every element of a 2D array safely, nest two loops, each using the appropriate length:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
Output:
1 2 3
4 5 6
7 8 9
Using matrix[row].length (rather than matrix[0].length) is a good habit because it correctly handles jagged arrays where rows have different lengths.
length With Jagged Arrays
A jagged array is an array of arrays where each row can have a different size. length on the outer array tells you the number of rows; length on each row tells you that row’s specific column count.
int[][] jagged = {
{1, 2},
{3, 4, 5, 6},
{7}
};
System.out.println("Rows: " + jagged.length); // 3
for (int i = 0; i < jagged.length; i++) {
System.out.println("Row " + i + " length: " + jagged[i].length);
}
Output:
Rows: 3
Row 0 length: 2
Row 1 length: 4
Row 2 length: 1
Passing Arrays to Methods
When you pass an array to a method, length travels with it — you never need to pass the size as a separate parameter.
public static int sum(int[] arr) {
int total = 0;
for (int i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
public static void main(String[] args) {
int[] values = {10, 20, 30, 40};
System.out.println("Sum: " + sum(values)); // Sum: 100
}
Output:
Sum: 100
This is a big advantage over languages like C where you must pass the array size separately.
length vs size() — Arrays vs Collections
If you later work with Java collections, note the naming difference:
| Type | How to get size |
|---|---|
int[], String[], any array | array.length (field) |
ArrayList, LinkedList, etc. | list.size() (method) |
String | str.length() (method) |
Warning: Calling
.length()on an array or.lengthon aStringis a compile-time error. Keep the table above handy until the distinction is second nature.
Under the Hood
When the JVM creates an array with new int[5], it allocates a block of memory on the heap. The first word of that block is the array header, which stores — among other things — the length value as a 32-bit integer. This is why array.length is an O(1) operation with no computation: it simply reads from a known offset in the array object’s header.
Because length is stored in the header as a final field (from the perspective of the Java Language Specification), the JIT compiler can treat it as a constant within a tight loop and avoid re-reading it from memory on every iteration. This is one reason why using arr.length directly in a loop condition is not slower than caching it in a local variable — the JIT is smart enough to handle it.
The bytecode instruction arraylength (opcode 0xBE) is what the compiler emits when it sees array.length. It pops an array reference from the operand stack and pushes back its length as an int. You can see this yourself using the javap tool.
Note: The
lengthfield can never exceedInteger.MAX_VALUE(2,147,483,647). In practice, available heap memory will be the binding constraint long before you reach that limit.
Quick Reference
// 1D array
int[] arr = new int[10];
int len = arr.length; // 10
// 2D array — rows
int[][] grid = new int[4][6];
int rows = grid.length; // 4
int cols = grid[0].length; // 6
// Empty array — safe, no exception
String[] empty = new String[0];
boolean isEmpty = (empty.length == 0); // true
// Checking before access — defensive pattern
if (arr.length > 0) {
System.out.println(arr[0]);
}
Related Topics
- Arrays — full introduction to declaring, creating, and initializing arrays
- Multidimensional Arrays — working with 2D and higher-dimensional arrays
- Jagged Arrays — arrays of arrays with unequal row lengths
- for-each Loop — the cleanest way to iterate when you don’t need the index
- Arrays Utility Class — sorting, searching, and comparing arrays with
java.util.Arrays - ArrayList — a resizable alternative to arrays whose size grows dynamically