skip to content

How do you get the size of an array in Java, and why is it a field rather than a method?

level: juniorimportance: must knowfreq 68%

answer

  1. a.length — field, no parentheses
  2. String.length(), List.size() — methods, with ()
  3. public final → immutable, can't assign
  4. 2-D: a.length=rows, a[i].length=that row
  5. null reference → NPE on .length

basics

~10 s

You read the public length field, like a.length (no parentheses). It tells you how many elements the array has. It is fixed for the array's lifetime and you cannot change it.

solid answer

~50 s

Arrays expose their size through a `public final` field named `length`, accessed as `a.length` with no parentheses — note this differs from `String.length()` (a method) and `List.size()` (a method), a frequent source of confusion. Because it is `final`, the value is fixed at creation and cannot be reassigned; this reflects the fact that array length is immutable. Valid indices run `0` to `a.length - 1`, so `length` is the standard loop bound. For a 2-D array, `a.length` is the number of rows and `a[i].length` is the length of row `i` (rows can differ in a jagged array). On a `null` array reference, reading `.length` throws `NullPointerException`, since there's no object to query. The field exists on the special array class the JVM synthesizes; it's a built-in property, not a normal user-defined member, which is why it's a field with magic-but-simple semantics rather than a method call.

code

java · 7 lines
java
int[] a = new int[5];
for (int i = 0; i < a.length; i++) { /* 0..4 */ }

int[][] m = new int[3][5];
int rows = m.length;      // 3
int cols = m[0].length;   // 5
// a.length = 10;         // compile error: length is final

go deeper

for a junior

Uses a.length (no parentheses) to get size and as a for-loop bound.

for a middle

Distinguishes length / length() / size(), knows it's final/immutable, and uses m[i].length for 2-D.

for a senior

Explains the public final field semantics, NPE on null, capacity-vs-used distinction, and jagged-array iteration.

for a principal

Discusses the JVM's synthesized array class and arraylength bytecode, why immutability is encoded as final, and the performance rationale for a field over a method.

## Reading the size Every Java array has a built-in, read-only property holding its element count, accessed as a **field** called `length`: ```java int[] a = new int[5]; int n = a.length; // 5 — note: NO parentheses ``` ## The classic confusion: length vs length() vs size() Three similar-looking things mean 'how many', and mixing them up is one of the most common Java mistakes: | Construct | How to get count | Form | |---|---|---| | Array | `a.length` | **field**, no `()` | | `String` | `s.length()` | **method**, with `()` | | Collections (`List`, `Set`, `Map`) | `c.size()` | **method**, with `()` | Writing `a.length()` on an array is a compile error; writing `s.length` on a String is also a compile error. Memorize: arrays use the bare field. ## Why a field, and why final The JVM creates a special hidden class for each array type, and `length` is a `public final int` member of it. Being **`final`** encodes the rule that **array length is immutable** — once created, the size never changes, so the value never needs to be writable. You cannot do `a.length = 10;` (compile error). To 'change the size' you allocate a new array and copy. Making it a field (not a method) is partly historical/performance-oriented: the JVM has a dedicated bytecode (`arraylength`) to fetch it in one cheap operation, and there's no user code to call. Conceptually it behaves like an immutable property. ## As a loop bound Because indices are `0..length-1`, `length` is the canonical bound: ```java for (int i = 0; i < a.length; i++) { ... } ``` Using `<=` here would read `a[length]`, which is out of range and throws `ArrayIndexOutOfBoundsException`. ## Multi-dimensional arrays For `int[][] m`, `m.length` is the number of **rows** (the outer array's length), and each `m[i].length` is the length of that row. In a jagged array rows can have different lengths, so you must use `m[i].length` per row rather than assuming a single column count: ```java for (int i = 0; i < m.length; i++) for (int j = 0; j < m[i].length; j++) ... m[i][j] ... ``` ## Null arrays `length` is queried on the array object. If the reference is `null`, `a.length` throws `NullPointerException` — there is no array to ask. Always ensure the reference is non-null (or use a zero-length array instead of `null`). ## length vs. how many elements you've 'used' `length` is the **capacity** (total slots), not how many you've meaningfully filled. An `int[10]` you only set 3 values in still reports `length == 10`; tracking 'used count' is your responsibility (this is exactly the bookkeeping `ArrayList` does for you). ## Bottom line `a.length` (field, no parens) gives the fixed element count; it's `public final`, throws NPE on a null reference, and is the right loop bound. Don't confuse it with `length()` or `size()`.

  • What is the difference between a.length, s.length(), and list.size()?
    a.length is a field (no parentheses) on arrays; s.length() is a method on String; list.size() is a method on collections. They all report a count but use different syntax — a very common mix-up.
  • For a 2-D array m, what do m.length and m[0].length give?
    m.length is the number of rows (the outer array's length); m[0].length is the number of columns in the first row. In a jagged array each row may have a different length, so you read m[i].length per row.

saying these in an interview costs you the question

  • Writing a.length() with parentheses on an array
  • Confusing array length with String.length() or List.size()
  • Trying to assign a.length = n to resize
  • Using <= a.length as a loop bound (off-by-one → AIOOBE)
  • Thinking length is the 'used count' rather than capacity

context