01 / 20
0 1 2 3 [0] [1] [2] [3]

Array Access
& Bounds

Learn to read and write array elements by index, understand zero-based indexing, and prevent the dreaded ArrayIndexOutOfBoundsException.

Java

What Is an Array?

An array is a fixed-size, ordered container that stores multiple values of the same type in contiguous memory. Each slot has a numeric index that lets you jump directly to any element in constant time.

42 17 93 8 ... [0] [1] [2] [3] first last

Zero-Based Indexing

Java arrays start counting at 0, not 1. An array of length \( n \) has valid indices from 0 to \( n - 1 \).

'A' 'B' 'C' 'D' 'E' 0 1 2 3 4 first index last index length = 5, valid range: 0 to 4

Why Bounds Matter

✓ Valid Access
Index is \( \geq 0 \) and \( < \texttt{length} \). The program reads or writes the value successfully.
✕ Out of Bounds
Index is \( < 0 \) or \( \geq \texttt{length} \). Java throws an ArrayIndexOutOfBoundsException and the program crashes.

The Access Rule

For an array arr of length \( n \):

Valid index i must satisfy:
\( 0 \le i < \texttt{arr.length} \)
1
Read: int x = arr[i]; copies the value at index \( i \) into variable x.
2
Write: arr[i] = 99; replaces the value at index \( i \) with 99.
3
Length: arr.length returns the total number of slots (read-only, no parentheses).

Valid vs. Invalid Indices

10 20 30 40 [0] [1] [2] [3] [-1] INVALID [4] INVALID
valid range: 0 to \( \texttt{length}-1 \)
negative ≥ length int[] arr = {10, 20, 30, 40}; // length = 4

Declaring vs. Accessing

Declaration Access / Update
Syntax int[] arr = new int[5]; arr[2] = 99;
Brackets mean "I want an array of this size" "Go to this index"
Number inside Total length (count of slots) Specific index (0-based position)
When it runs Once, at creation Every time you read/write

Step-by-Step Safe Access

1
Know the length. Check arr.length to know how many elements exist.
2
Compute index range. Valid indices run from 0 to \( \texttt{arr.length} - 1 \).
3
Check loop conditions. Use i < arr.length (strict less-than), never i <= arr.length.
4
Guard edge cases. Before accessing arr[i-1] or arr[i+1], verify those shifted indices are also in range.
5
Test boundaries. Mentally (or actually) trace the first iteration (\( i = 0 \)) and last iteration (\( i = \texttt{length} - 1 \)).

Example 1: Reading Elements

int[] scores = {85, 92, 78, 95, 88}; System.out.println(scores[0]); // 85 (first) System.out.println(scores[2]); // 78 (third) System.out.println(scores[4]); // 88 (last)
85 92 78 95 88 [0] [1] [2] [3] [4] read read read

Example 2: Updating Elements

String[] colors = {"red", "green", "blue"}; colors[1] = "yellow"; // overwrite index 1 // colors is now {"red", "yellow", "blue"} System.out.println(colors[1]); // "yellow"
BEFORE: "red" "green" "blue" overwrite AFTER: "red" "yellow" "blue" [0] [1] [2]

Example 3: Loop Traversal

double[] temps = {72.1, 68.5, 75.3, 69.8}; double sum = 0; for (int i = 0; i < temps.length; i++) { sum += temps[i]; } double avg = sum / temps.length; System.out.println(avg); // 71.425

The Off-by-One Trap

// WRONG: uses <= instead of < for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); // CRASH on last iteration! } // CORRECT: uses strict < for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); // safe }
0 1 2 3 4
valid: \( i < 4 \)
CRASH
\( i \le 4 \) allows this
length = 4

Accessing Neighbors

Sometimes you need to compare adjacent elements. When accessing arr[i-1] or arr[i+1], the shifted index must also be in bounds.

// Find pairs that sum to 100 for (int i = 0; i < arr.length - 1; i++) { if (arr[i] + arr[i + 1] == 100) { System.out.println("Found at " + i); } }

Common Mistakes

✕ Using <= in loop
i <= arr.length includes the out-of-bounds index. Use i < arr.length instead.
✕ Starting at 1
for (int i = 1; ...) skips the first element at index 0. Always start at 0 unless intentional.
✕ Confusing length and last index
arr[arr.length] is always invalid. The last element is at arr[arr.length - 1].

Quick Reference Table

Operation Syntax Result
Declare + init int[] a = {5, 10, 15}; 3 elements, indices 0-2
Read element int x = a[1]; x = 10
Write element a[2] = 99; a becomes {5, 10, 99}
Get length a.length 3 (no parentheses)
Last element a[a.length - 1] Value at index 2
Safe loop for (i=0; i<a.length; i++) Visits indices 0, 1, 2

Question 1 of 5

Given int[] nums = {3, 7, 1, 9, 4};, what is the value of nums[3]?

Question 2 of 5

What does arr[arr.length] do when arr has 6 elements?

Question 3 of 5

What is the output of this code?

Question 4 of 5

Which loop correctly prints all elements of String[] names without going out of bounds?

Question 5 of 5

What is printed?