AP Computer Science A · Unit 4: Data Collections
4.5 2D Array Creation and Access
Creating 2D Arrays
A 2D array is an array of arrays, often visualized as a grid of rows and columns. Declare with `int[][] arr = new int[rows][cols];` to create a fixed-size grid, or use array initializer syntax like `{{1,2},{3,4}}`. Java stores 2D arrays as arrays of array references, so rows can technically have different lengths (jagged arrays).
Accessing Elements
Access an element with arr[row][col], where the first index selects the row and the second selects the column. Indices are zero-based, so a grid with `numRows` rows and `numCols` columns has valid indices 0 through `numRows-1` and 0 through `numCols-1`. Going out of these bounds throws an ArrayIndexOutOfBoundsException.
Traversing with Nested Loops
Process every element using nested for loops: the outer loop iterates over rows (`arr.length`), and the inner loop iterates over columns (`arr[row].length`). This ordering matters — using `arr[row].length` handles jagged arrays correctly, since row lengths may vary.
Key terms
- 2D array
- An array of arrays, commonly used to represent a grid of rows and columns.
- Syntax to declare a 2D array
- type[][] name = new type[rows][cols]; e.g., int[][] arr = new int[3][4];
- Accessing an element
- Use arr[row][col], where row and col are zero-based indices.
- Jagged array
- A 2D array where each row can have a different number of columns, since rows are independent arrays.
- Nested for loop traversal
- Outer loop runs through rows (arr.length), inner loop runs through columns (arr[row].length) to visit every element.
Try an AP-style question
Code
int[][] m = new int[3][4];
What is m.length?
- 7
- 4
- 3
- 12
Show the answer
C. Number of rows.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 4.5 free in APrep