Topic 4.11 Notes – 2D Array Creation and Access
1. What a 2D Array Is
A 2D array in Java is an array of arrays.
That means:
- The main array holds rows.
- Each row is itself a 1D array.
- Each element inside that row is a value.
If we write:
int[][] grid = new int[3][4];
grid.length→ number of rows →3grid[0].length→ number of columns in row 0 →4
On the AP exam, 2D arrays are always rectangular, meaning:
- Every row has the same number of columns.
- No jagged arrays are tested.
The size is fixed when created. You cannot resize it later.
2D arrays can store:
- Primitives like
int,double,boolean - Object references like
Stringor custom class objects
2. Creating and Initializing 2D Arrays
Using new with Dimensions
int[][] board = new int[2][3];
This creates:
- 2 rows
- 3 columns per row
Every element is automatically set to a default value:
| Type | Default Value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
| reference types | null |
Students sometimes forget this and think the array is “empty.” It isn’t. It’s filled with defaults.
Using an Initializer List
int[][] scores = {
{7, 8, 9},
{10, 11, 12}
};
Each inner {} represents a row.
- Number of rows = number of inner lists
- Number of columns = number of elements inside each row
This is cleaner when you already know the values.
3. Accessing Elements and Row-Major Order
Access format:
arr[row][col]
The AP exam follows row-major order:
- First index → row
- Second index → column
If you want the element in row 1, column 2:
arr[1][2]
Say it in your head: row first, column second.
Most mistakes happen because students flip them.
Accessing an Entire Row
arr[1]
This gives you the whole second row as a 1D array.
That’s why:
arr[row].length
works. You’re asking, “How long is this row array?”
Using .length Correctly
This is where MC questions love to trap people.
arr.length→ number of rowsarr[row].length→ number of columns in that row
Valid indexes:
- Rows →
0througharr.length - 1 - Columns →
0througharr[row].length - 1
If you go outside those ranges, you get:
ArrayIndexOutOfBoundsException
Classic mistake inside nested loops:
for (int col = 0; col < arr.length; col++) // WRONG
Correct version:
for (int col = 0; col < arr[row].length; col++)
Rows use arr.length.
Columns use arr[row].length.
4. Putting It All Together
The standard traversal pattern looks like this:
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
// process arr[row][col]
}
}
Outer loop → rows
Inner loop → columns
The inner loop finishes completely before the row changes. That detail matters when tracing code on quizzes.
On FRQ 4, you almost always:
- Count values
- Sum values
- Modify elements
- Search for something specific
Every one of those uses this same nested structure.