Arrays (Single & Multi-Dimensional)
Arrays are fixed-size containers that store elements of the same data type. Once initialized, their lengths cannot be changed.
1 Declaring, Initializing, and Array Memory
In Java, arrays are objects. Memory space is allocated on the heap, and variables hold reference addresses pointing to that space. Declaring an array can be done in two ways:
- `int[] numbers = new int[5];` (Allocates size but contents default to 0)
- `int[] numbers = {1, 2, 3, 4, 5};` (Inline literal initialization)
⚠️ Warning: Accessing an index outside of `0` to `length - 1` throws an `ArrayIndexOutOfBoundsException`. Always guard index parameters.
2 Matrix iteration & Safe Array Copies
Because arrays are references, writing `int[] copy = original;` merely copies the address. Any change in `copy` alters `original`. To perform a true, safe copy, use `System.arraycopy()` or `Arrays.copyOf()`. Let's test single arrays, matrices, and copying:
Java — Arrays & Matrices
▶ Run Code
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Single-dimensional array
int[] scores = {90, 85, 78, 92};
System.out.println("Original array: " + Arrays.toString(scores));
// Safe array copy
int[] safeCopy = Arrays.copyOf(scores, scores.length);
safeCopy[0] = 100;
System.out.println("Modified copy: " + Arrays.toString(safeCopy));
System.out.println("Original untouched: " + Arrays.toString(scores));
// Multi-dimensional array (2D Matrix: Rows x Columns)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("Iterating over 2D Matrix:");
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
3 Code Challenge
Challenge: Create an array of 6 integers. Initialize them with random scores. Write a loop to find and print the maximum value in the array. Then create a 2D array of size 2x2 representing a coordinates grid, fill it, and output all points.