Arrays can store primitive data or object references, and when created with new, their elements are initialized to 0 for int, 0.0 for double, false for boolean, and null for reference types.
Arrays represent collections of related data of the same data type, with a fixed size that cannot be changed after creation.
Initializer lists can be used to create and initialize arrays.
Elements are accessed or modified using square brackets ([ ]) and an index (e.g., array[index]).
Valid index values range from 0 to array length - 1; values outside this range throw an ArrayIndexOutOfBoundsException.
// Initializing and accessing arrays
public class ArrayExample {
public static void main(String[] args) {
// Using the 'new' keyword
int[] numbers = new int[5]; // Array of size 5
System.out.println("Default value at index 0: " + numbers[0]); // Output: 0
// Using an initializer list
int[] scores = {90, 80, 85, 70, 95};
// Accessing and modifying array elements
System.out.println("Score at index 2: " + scores[2]); // Output: 85
scores[2] = 88; // Modify the value
System.out.println("Updated score at index 2: " + scores[2]); // Output: 88
// ArrayIndexOutOfBoundsException example
try {
System.out.println(scores[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Iteration (loops) can be used to access all the elements in an array, traversing the array.
Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
Since the index for an array starts at 0 and ends at the number of elements − 1, “off by one” errors are easy to make when traversing an array, resulting in an ArrayIndexOutOfBoundsException being thrown.
// Traversing an array using loops
public class ArrayTraversal {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Indexed for loop
System.out.println("Using an indexed for loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// While loop
System.out.println("Using a while loop:");
int index = 0;
while (index < numbers.length) {
System.out.println("Element at index " + index + ": " + numbers[index]);
index++;
}
// Off by one error demonstration
try {
System.out.println(numbers[numbers.length]); // Accessing index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
An enhanced for loop, also called a for-each loop, can be used to loop through an array without using an index variable.
An enhanced for loop header includes a variable, referred to as the enhanced for loop variable, that holds each value in the array.
For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop.
// Using an enhanced for loop to traverse an array
public class EnhancedForLoopExample {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
// Enhanced for loop
System.out.println("Using an enhanced for loop:");
for (int num : numbers) {
System.out.println("Value: " + num);
}
// Assigning a value to the loop variable
System.out.println("Attempting to modify the loop variable:");
for (int num : numbers) {
num = num * 2; // Modifying the loop variable
System.out.println("Modified value: " + num);
}
// Printing the array to show it remains unchanged
System.out.println("Array after enhanced for loop:");
for (int num : numbers) {
System.out.println("Value: " + num);
}
// Rewriting an enhanced for loop as an indexed for loop
System.out.println("Rewriting as an indexed for loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Value at index " + i + ": " + numbers[i]);
}
}
}