Skip to content

4.2 Accessing Array Elements

Once an array is initialized, we need to work with its individual elements. Accessing array elements is fundamental to array manipulation and forms the basis for most array operations.

Array Indexing

Zero-Based Indexing

Java uses zero-based indexing, meaning the first element is at position 0, the second at position 1, and so on.

java
int[] numbers = {10, 20, 30, 40, 50};
// Index:        0    1   2   3   4
// Position:     1st 2nd 3rd 4th 5th

Valid Index Range

  • First element: index 0
  • Last element: index array.length - 1
  • Total elements: array.length
java
int[] arr = new int[5];
// Valid indices: 0, 1, 2, 3, 4
// Invalid indices: -1, 5, 6, etc.

Accessing Elements

Basic Element Access

java
// Syntax: arrayName[index]
int[] scores = {85, 92, 78, 90, 88};

// Access individual elements
int firstScore = scores[0];     // 85
int thirdScore = scores[2];     // 78
int lastScore = scores[4];      // 88

System.out.println("First score: " + firstScore);
System.out.println("Third score: " + thirdScore);

Using Variables as Indices

java
int[] numbers = {10, 20, 30, 40, 50};
int index = 2;

System.out.println(numbers[index]);     // Output: 30
System.out.println(numbers[index + 1]); // Output: 40

Mathematical Expressions in Indices

java
int[] data = {1, 4, 9, 16, 25};
System.out.println(data[2 * 2]);        // Output: 25 (data[4])
System.out.println(data[3 - 1]);        // Output: 9 (data[2])

Modifying Elements

Changing Array Values

java
String[] colors = {"Red", "Green", "Blue"};

// Modify elements
colors[0] = "Crimson";
colors[1] = "Emerald";
colors[2] = "Navy";

System.out.println(colors[0]);  // Output: Crimson
System.out.println(colors[1]);  // Output: Emerald

Incrementing/Decrementing Values

java
int[] counters = {5, 10, 15, 20};

// Increment the second element
counters[1]++;                   // counters[1] becomes 11
counters[2] = counters[2] + 5;   // counters[2] becomes 20
counters[3] -= 3;                // counters[3] becomes 17

System.out.println(counters[1]); // Output: 11

Swapping Elements

java
int[] numbers = {1, 2, 3, 4, 5};

// Swap first and last elements
int temp = numbers[0];
numbers[0] = numbers[4];
numbers[4] = temp;

System.out.println("First: " + numbers[0]);  // Output: 5
System.out.println("Last: " + numbers[4]);   // Output: 1

Iterating Through Arrays

1. For Loop (Most Common)

java
int[] numbers = {10, 20, 30, 40, 50};

// Forward iteration
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element at index " + i + ": " + numbers[i]);
}

2. Enhanced For Loop (For-Each)

java
int[] numbers = {10, 20, 30, 40, 50};

// Read-only iteration (cannot modify array)
for (int number : numbers) {
    System.out.println("Number: " + number);
}

3. Backward Iteration

java
int[] numbers = {10, 20, 30, 40, 50};

// Reverse order
for (int i = numbers.length - 1; i >= 0; i--) {
    System.out.println("Element at index " + i + ": " + numbers[i]);
}

4. While Loop

java
int[] numbers = {10, 20, 30, 40, 50};
int i = 0;

while (i < numbers.length) {
    System.out.println("Element: " + numbers[i]);
    i++;
}

Array Length Property

The length Property

Every array has a public final field called length that stores the size of the array.

java
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[10];

System.out.println("Numbers length: " + numbers.length);  // Output: 5
System.out.println("Names length: " + names.length);      // Output: 10

Using Length in Loops

java
// Safe iteration using length property
int[] data = {10, 20, 30, 40, 50};

for (int i = 0; i < data.length; i++) {
    System.out.println(data[i]);
}

// Last element access
int lastElement = data[data.length - 1];
System.out.println("Last element: " + lastElement);

Common Operations

1. Finding Maximum and Minimum

java
int[] numbers = {45, 12, 78, 23, 56, 91, 34};

int max = numbers[0];
int min = numbers[0];

for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
    if (numbers[i] < min) {
        min = numbers[i];
    }
}

System.out.println("Maximum: " + max);  // Output: 91
System.out.println("Minimum: " + min);  // Output: 12

2. Calculating Sum and Average

java
double[] prices = {19.99, 29.99, 15.49, 39.99, 24.99};

double sum = 0;
for (double price : prices) {
    sum += price;
}

double average = sum / prices.length;

System.out.println("Total: $" + sum);           // Output: Total: $130.45
System.out.println("Average: $" + average);     // Output: Average: $26.09

3. Searching for an Element

java
String[] fruits = {"Apple", "Banana", "Orange", "Grape", "Mango"};
String target = "Orange";
boolean found = false;
int position = -1;

for (int i = 0; i < fruits.length; i++) {
    if (fruits[i].equals(target)) {
        found = true;
        position = i;
        break;
    }
}

if (found) {
    System.out.println(target + " found at index " + position);
} else {
    System.out.println(target + " not found in the array");
}

4. Counting Occurrences

java
int[] numbers = {1, 2, 3, 2, 4, 2, 5, 2};
int target = 2;
int count = 0;

for (int number : numbers) {
    if (number == target) {
        count++;
    }
}

System.out.println(target + " appears " + count + " times"); // Output: 2 appears 4 times

5. Copying Arrays

java
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];

// Manual copying
for (int i = 0; i < original.length; i++) {
    copy[i] = original[i];
}

// Verify copy
for (int i = 0; i < copy.length; i++) {
    System.out.println("copy[" + i + "] = " + copy[i]);
}

Error Handling

ArrayIndexOutOfBoundsException

This exception occurs when trying to access an invalid index (negative or ≥ array length).

java
int[] numbers = {10, 20, 30};

// These will cause ArrayIndexOutOfBoundsException
// System.out.println(numbers[-1]);  // Negative index
// System.out.println(numbers[5]);   // Index beyond length
// System.out.println(numbers[3]);   // Equal to length (invalid)

// Safe access with bounds checking
int index = 5;
if (index >= 0 && index < numbers.length) {
    System.out.println(numbers[index]);
} else {
    System.out.println("Invalid index: " + index);
}

NullPointerException

Occurs when trying to access elements of a null array reference.

java
int[] numbers = null;

// This will cause NullPointerException
// System.out.println(numbers[0]);

// Safe access
if (numbers != null && numbers.length > 0) {
    System.out.println(numbers[0]);
} else {
    System.out.println("Array is null or empty");
}

Complete Examples

Example 1: Student Grade Management

java
public class GradeManager {
    public static void main(String[] args) {
        int[] grades = {85, 92, 78, 90, 88, 76, 95, 82};
        
        // Calculate statistics
        int sum = 0;
        int highest = grades[0];
        int lowest = grades[0];
        
        for (int grade : grades) {
            sum += grade;
            if (grade > highest) highest = grade;
            if (grade < lowest) lowest = grade;
        }
        
        double average = (double) sum / grades.length;
        
        System.out.println("Grade Statistics:");
        System.out.println("Total students: " + grades.length);
        System.out.println("Average grade: " + average);
        System.out.println("Highest grade: " + highest);
        System.out.println("Lowest grade: " + lowest);
        
        // Display all grades
        System.out.println("\nAll grades:");
        for (int i = 0; i < grades.length; i++) {
            System.out.println("Student " + (i + 1) + ": " + grades[i]);
        }
    }
}

Example 2: Temperature Analysis

java
public class TemperatureAnalyzer {
    public static void main(String[] args) {
        double[] temperatures = {72.5, 68.3, 75.1, 79.8, 82.4, 77.9, 71.2};
        
        // Find days above average
        double sum = 0;
        for (double temp : temperatures) {
            sum += temp;
        }
        double average = sum / temperatures.length;
        
        System.out.println("Weekly Temperature Analysis");
        System.out.println("Average temperature: " + average + "°F");
        System.out.println("\nDays above average:");
        
        for (int i = 0; i < temperatures.length; i++) {
            if (temperatures[i] > average) {
                System.out.println("Day " + (i + 1) + ": " + temperatures[i] + "°F");
            }
        }
    }
}

Example 3: Array Reversal

java
public class ArrayReversal {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        System.out.println("Original array:");
        printArray(numbers);
        
        // Reverse the array
        for (int i = 0; i < numbers.length / 2; i++) {
            int temp = numbers[i];
            numbers[i] = numbers[numbers.length - 1 - i];
            numbers[numbers.length - 1 - i] = temp;
        }
        
        System.out.println("Reversed array:");
        printArray(numbers);
    }
    
    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}

Common Mistakes and Best Practices

Common Mistakes

  1. Off-by-one errors

    java
    int[] arr = new int[5];
    // Wrong: for (int i = 0; i <= arr.length; i++)
    // Correct: for (int i = 0; i < arr.length; i++)
  2. Using enhanced for loop for modification

    java
    int[] numbers = {1, 2, 3};
    // This doesn't modify the array:
    for (int num : numbers) {
        num = num * 2;  // Only changes local variable
    }
    // Use regular for loop instead
  3. Assuming arrays are passed by value

    java
    // Arrays are reference types - modifications in methods affect original
    public static void modifyArray(int[] arr) {
        arr[0] = 100;  // This changes the original array
    }

Best Practices

  1. Always check array bounds

    java
    if (index >= 0 && index < array.length) {
        // Safe to access array[index]
    }
  2. Use enhanced for loop for read-only access

    java
    // More readable for simple iterations
    for (String name : names) {
        System.out.println(name);
    }
  3. Cache array length in loops for large arrays

    java
    int length = largeArray.length;
    for (int i = 0; i < length; i++) {
        // operations
    }

Summary

  • Arrays use zero-based indexing: first element at index 0
  • Access elements using array[index] syntax
  • Use loops to iterate through arrays efficiently
  • The length property provides the array size
  • Always check bounds to avoid ArrayIndexOutOfBoundsException
  • Different loop types serve different purposes
  • Arrays are reference types - modifications affect the original

In the next section, we'll explore multi-dimensional arrays and how to work with complex data structures.