Metadata Card
- Prerequisites: Ch4 (Control Flow), Ch5 (Methods)
- Estimated time: 55 min
- Core difficulty:
- Reading mode: Steady progress
- Completion marker: Can declare, initialize, and iterate over arrays; understand index vs value; use multi-dimensional arrays
The Breakthrough · Tracing the Origins
A variable holds one value. What if you need a hundred? An array is a contiguous block of memory that holds multiple values of the same type.
Declaring and Initializing
// Declaration and allocation
int[] numbers = new int[5]; // [0, 0, 0, 0, 0]
// With initial values
int[] scores = {85, 92, 78, 90, 88};
// Using the new keyword with values
int[] prices = new int[]{10, 20, 30};Indexing
int[] scores = {85, 92, 78};
System.out.println(scores[0]); // 85 (first element)
System.out.println(scores[1]); // 92
System.out.println(scores[2]); // 78
scores[1] = 95; // Modify
System.out.println(scores[1]); // 95Critical: Array indices start at 0. The last index is length - 1. Accessing outside this range throws ArrayIndexOutOfBoundsException.
Length and Iteration
int[] arr = {10, 20, 30, 40, 50};
System.out.println("Length: " + arr.length); // 5
// Traditional for loop
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// Enhanced for loop (for-each)
for (int value : arr) {
System.out.println(value);
}Memory Layout
Stack: scores (reference)
|
Heap: [85] [92] [78] [90] [88]
0 1 2 3 4The variable scores on the stack points to the array object on the heap.
Common Operations
int[] a = {1, 2, 3};
int[] b = a; // Both reference the SAME array
b[0] = 99;
System.out.println(a[0]); // 99! (changed)
// Copy: use Arrays.copyOf
int[] copy = Arrays.copyOf(a, a.length);
// Sort
Arrays.sort(arr);
// Fill
Arrays.fill(arr, 0); // Fill all with 0
// Search (must be sorted first)
int index = Arrays.binarySearch(arr, 42);Multi-dimensional Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[0][1]); // 2
System.out.println(matrix[1][2]); // 6
// Iteration
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}Final Challenge
- Write a method that finds the maximum value in an int array
- Write a method that reverses an array in-place
- Implement linear search: find the index of a target value, return -1 if not found
- Create a multiplication table as a 2D array (9x9)
Traveler's Notes
Arrays hold multiple values of the same type in contiguous memory.
Index starts at 0, ends at length-1.
Arrays in Java are objects on the heap; the variable holds a reference.
Array copying creates an independent copy; reference assignment shares the same array.
For-each loops (for (int x : arr)) are readable but don't give you the index.