Memra

Accessing & iterating: indexes, .length, and bounds

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.

NORMAL ~/memra/learn/java-from-zero/accessing-arrays utf-8 LF