Array Access
& Bounds
Learn to read and write array elements by index, understand zero-based indexing, and prevent the dreaded ArrayIndexOutOfBoundsException.
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.
Zero-Based Indexing
Java arrays start counting at 0, not 1. An array of length \( n \) has valid indices from 0 to \( n - 1 \).
Why Bounds Matter
The Access Rule
For an array arr of length \( n \):
int x = arr[i]; copies the value at index \( i \) into variable x.arr[i] = 99; replaces the value at index \( i \) with 99.arr.length returns the total number of slots (read-only, no parentheses).Valid vs. Invalid Indices
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
arr.length to know how many elements exist.i < arr.length (strict less-than), never i <= arr.length.arr[i-1] or arr[i+1], verify those shifted indices are also in range.Example 1: Reading Elements
Example 2: Updating Elements
Example 3: Loop Traversal
The Off-by-One Trap
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.
Common Mistakes
i <= arr.length includes the out-of-bounds index. Use i < arr.length instead.for (int i = 1; ...) skips the first element at index 0. Always start at 0 unless intentional.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
Consider this code:
int[] data = new int[4];
data[0] = 10;
data[1] = 20;
data[2] = 30;
data[3] = 40;
for (int i = 1; i <= data.length; i++) {
System.out.print(data[i] + " ");
}
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
Consider this code:
int[] vals = {5, 10, 15, 20, 25};
vals[2] = vals[0] + vals[4];
System.out.println(vals[2]);
What is printed?