Arrays: Fixed-Size, Typed, and Zero-Indexed
Java's array type — how to declare, fill, and iterate one, why its length is fixed forever, and the exception you'll hit constantly until you internalize the valid-index range.
What you'll learn
- Declare, initialize, and iterate a Java array correctly
- Explain why an array's length cannot change after creation
- Predict and avoid ArrayIndexOutOfBoundsException
Prerequisites
Explanation
A Java array is a fixed-size, homogeneous (single-type) container, created with a size that's locked in forever: int[] scores = new int[5]; allocates space for exactly 5 ints, all initialized to 0 (the default value for numeric types; false for boolean, null for reference-type arrays). There is no way to "grow" this array — you can only create a brand-new, larger array and copy the old contents into it, which is exactly what the ArrayList class (covered in the next lesson) does internally so you don't have to do it by hand.
Arrays are zero-indexed: valid indices for a 5-element array run 0 through 4 — scores[5] is out of bounds and throws ArrayIndexOutOfBoundsException at runtime, not a compile error, because the compiler has no way to know an index's value ahead of time in the general case. scores.length (a field, not a method — no parentheses) always gives the array's fixed size, and scores[i] reads or writes the element at index i. Iterating with a for-each loop (for (int score : scores)) is preferred whenever you don't need the index, since it can never produce an out-of-bounds access.
Java also supports multi-dimensional arrays — int[][] grid = new int[3][4]; is really an array of 3 arrays, each of length 4 (a "jagged" array, since each inner array's length is independently settable: int[][] jagged = new int[3][]; jagged[0] = new int[2];). Arrays are reference types, so passing one to a method passes the reference, and mutating an element through that reference is visible to the caller — the same rule from the methods lesson, applied to arrays specifically.
Example
A fixed-size array modeled with a JS array that's frozen at a set length -- the index-bounds rule is identical to Java's.
function makeFixedArray(size, defaultValue) {
return new Array(size).fill(defaultValue);
}
const scores = makeFixedArray(5, 0);
scores[0] = 90;
console.log(scores); // [90, 0, 0, 0, 0]
console.log(scores.length); // 5 -- fixed regardless of what you assign into existing slots
function readAt(arr, index) {
if (index < 0 || index >= arr.length) {
throw new Error("ArrayIndexOutOfBoundsException: index " + index + " out of bounds for length " + arr.length);
}
return arr[index];
}
console.log(readAt(scores, 4)); // 0 -- valid, last index
readAt(scores, 5); // throws -- 5 is out of bounds for a 5-element arrayTry it yourself
Change readAt(scores, 5) to readAt(scores, 4) and confirm it no longer throws.
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Guided exercise
Guided exercise
Write isValidIndex(arrayLength, index) modeling Java's bounds rule exactly: true if 0 <= index < arrayLength, false otherwise (including negative indices).
Checks: index 0 is valid · the last valid index (length - 1) is valid · index equal to length is invalid · negative index is invalid
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Independent exercise
Independent exercise
Write sumArray(numbers) using a for-each-style loop (for...of in JS, the equivalent of Java's for-each) that returns the sum of all elements, and maxArray(numbers) that returns the largest element (throw an Error if the array is empty, modeling how you'd guard this in Java).
Checks: sums a 3-element array correctly · sums an empty array to 0 · finds the max of an unordered array · throws on an empty array for maxArray
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Common mistakes
- Using scores.length() with parentheses -- length is a field on arrays, not a method (Strings and Lists, by contrast, do use .length()/.size() as methods).
- Looping with `i <= arr.length` instead of `i < arr.length` -- off-by-one, throws ArrayIndexOutOfBoundsException on the last iteration.
- Expecting `int[] a = new int[5]; a = new int[10];` to 'resize' the original array -- it doesn't; it makes a now point at a completely new, separate array, and the original 5-element array (and anyone else still referencing it) is unaffected.
Knowledge check
Takeaway
A Java array's size is fixed forever at creation; 'resizing' always means creating a new array and copying, and every index access is bounds-checked at runtime, throwing ArrayIndexOutOfBoundsException rather than silently reading garbage or growing.
Summary
Arrays are fixed-size, zero-indexed, homogeneous containers. length is a field, not a method. For-each loops are the safest way to iterate when you don't need the index, since they can never go out of bounds.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.