Course contentsShow
← Java
Lesson 244 of 2,8706. ArraysFree lesson

Accessing Array Elements with Index Notation

Learn how to read and write array elements using bracket notation and zero-based indexing.

Accessing Array Elements with Index Notation

What you'll learn: How to read from and write to specific positions in an array using bracket notation and zero-based indexing.

The Core Idea

Once you've created an array, you need a way to interact with individual elements stored inside it. Java provides index notation using square brackets [] to both read and modify array elements. Arrays use zero-based indexing, meaning the first element is at position 0, the second at position 1, and so on.

Think of an array like a row of numbered lockers. To access what's inside a specific locker, you need to know its number. In Java's system, the lockers are numbered starting from zero, not one.

Reading Array Elements

To retrieve a value from an array, use the array name followed by the index in brackets:

int[] scores = {85, 92, 78, 90, 88};
int firstScore = scores[0];  // 85
int thirdScore = scores[2];  // 78

Writing to Array Elements

You can also assign new values to array positions using the same bracket notation:

int[] scores = {85, 92, 78, 90, 88};
scores[1] = 95;  // Changes second element from 92 to 95
scores[4] = 100; // Changes last element from 88 to 100

Zero-Based Indexing

The valid index range for an array is 0 to length - 1. For an array with 5 elements, valid indexes are 0, 1, 2, 3, 4. Attempting to access scores[5] would cause an error because that position doesn't exist.

int[] data = new int[3];
data[0] = 10;  // Valid
data[2] = 30;  // Valid (last element)
// data[3] = 40;  // Error! Index out of bounds

Key Takeaway: Use arrayName[index] to read or write elements, remembering that arrays start counting at zero and the last valid index is always length - 1.