Accessing Array Elements

Arrays provide a simple way to store and access elements sequentially using indexing. Each element in an array is assigned a unique position, or index, which starts from 0 and goes up to array.length - 1. Understanding how to access and modify array elements with indexing is crucial for working with arrays effectively.

Accessing Array Elements by Index

To access an element, you use the array name followed by square brackets containing the index of the desired element:

int[] numbers = {10, 20, 30, 40, 50};
int firstElement = numbers[0]; // Accesses the first element, 10
int thirdElement = numbers[2]; // Accesses the third element, 30

System.out.println("First element: " + firstElement); // Output: 10
System.out.println("Third element: " + thirdElement); // Output: 30

If you attempt to access an index outside the array’s bounds (e.g., numbers[-1] or numbers[5]), Java throws an ArrayIndexOutOfBoundsException.

Modifying Array Elements by Index

You can modify an array element by assigning a new value to it using its index. This allows you to dynamically change the content of the array after its initialization.

int[] numbers = {10, 20, 30, 40, 50};
numbers[1] = 25; // Updates the second element to 25

System.out.println("Updated second element: " + numbers[1]); // Output: 25

In this example, numbers[1] changes from 20 to 25, modifying the array in place.

Example of Accessing and Modifying Elements in a Loop

When working with arrays, it’s common to use loops to access and modify each element. A for loop or enhanced for loop is often used to iterate over the array:

int[] scores = {70, 85, 90, 100};

// Accessing elements
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score at index " + i + ": " + scores[i]);
}

// Modifying elements
for (int i = 0; i < scores.length; i++) {
    scores[i] += 5; // Adds 5 to each score
}

System.out.println("Scores after modification:");
for (int score : scores) {
    System.out.println(score); // Updated scores
}