Memra

Accessing & iterating: indexes, .length, and bounds

◈ 4 cards

Zero-based indexing, the .length field, for vs for-each, and the out-of-bounds trap.

Reading and writing array elements

Array indexes start at 0 and run to length − 1:

int[] nums = {10, 20, 30};
System.out.println(nums[0]);  // 10
System.out.println(nums[2]);  // 30
nums[1] = 99;                  // write

The element count is nums.length — a public final field, not a method call. Writing nums.length() is a compile error. This is one of the most-tested distinctions on the OCP exam: contrast String.length() (a method, with parentheses) with array.length (a field, no parentheses).

Iterating with an indexed for:

for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

Iterating with an enhanced for (for-each) — cleaner when you don't need the index:

for (int n : nums) {
    System.out.println(n);
}

Accessing an index that is negative or ≥ length throws ArrayIndexOutOfBoundsException at runtime — not a compile error.

012nums1020300 .. length-1nums[1] = 99109930nums.length is 3
Only positions 0 through length − 1 exist. Writing nums[1] = 99 replaces one slot in place; the array itself is the same object and the same length.
expressionwhat it isresultnums.lengtha final fieldyes — 3nums.length()no such membercompile error"abc".length()a String methodyes — 3nums[3]index past the endthrows at run time
An array exposes length as a field; String exposes length() as a method. Confusing them fails at compile time — reading past the last index fails only when the line runs.
NORMAL ~/memra/learn/java-from-zero/accessing-arrays utf-8 LF