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.
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
int[] arr = new int[5];
// Valid indices: 0, 1, 2, 3, 4
// Invalid indices: -1, 5, 6, etc.
Accessing Elements
Basic Element Access
// 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
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
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
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
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
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)
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)
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
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
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.
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
// 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
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
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
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
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
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).
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.
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
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
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
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
Off-by-one errors
javaint[] arr = new int[5]; // Wrong: for (int i = 0; i <= arr.length; i++) // Correct: for (int i = 0; i < arr.length; i++)
Using enhanced for loop for modification
javaint[] 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
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
Always check array bounds
javaif (index >= 0 && index < array.length) { // Safe to access array[index] }
Use enhanced for loop for read-only access
java// More readable for simple iterations for (String name : names) { System.out.println(name); }
Cache array length in loops for large arrays
javaint 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.