Declaring and creating 2D arrays
Using `new`
java
// Create a 3-row, 4-column grid of integers
int[][] grid = new int[3][4];
col 0 col 1 col 2 col 3
row 0 [ 0 0 0 0 ]
row 1 [ 0 0 0 0 ]
row 2 [ 0 0 0 0 ]
Using an initializer list
java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]
Accessing elements: `grid[row][col]`
java
int[][] matrix = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
System.out.println(matrix[0][0]); // 10 (row 0, col 0)
System.out.println(matrix[1][2]); // 60 (row 1, col 2)
System.out.println(matrix[2][1]); // 80 (row 2, col 1)
matrix[1][1] = 99; // change center element
// Row 1 is now: [40, 99, 60]
Getting dimensions
java
int[][] grid = new int[3][4]; // 3 rows, 4 columns
int rows = grid.length; // 3 (number of rows)
int cols = grid[0].length; // 4 (number of columns in first row)
grid → [ row0, row1, row2 ]
↓ ↓ ↓
[0,0,0,0] [0,0,0,0] [0,0,0,0]
Memory model
java
int[][] table = {
{1, 2},
{3, 4},
{5, 6}
};
table → [ ref0, ref1, ref2 ]
↓ ↓ ↓
[1, 2] [3, 4] [5, 6]
Practical example: Seating chart
java
public class SeatingChart {
public static void main(String[] args) {
String[][] seats = {
{"Alice", "Bob", "Charlie"},
{"Diana", "Eve", "Frank"},
{"Grace", "Henry", "Ivy"}
};
// Access specific seat
System.out.println("Row 1, Seat 2: " + seats[1][2]); // Frank
// Move a student
String temp = seats[0][1]; // Bob
seats[0][1] = seats[2][0]; // Grace moves to Bob's seat
seats[2][0] = temp; // Bob moves to Grace's seat
// Print the chart
System.out.println("Rows: " + seats.length); // 3
System.out.println("Cols: " + seats[0].length); // 3
}
}
Common index patterns
Jagged arrays (different row lengths)
java
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // row 0 has 2 elements
jagged[1] = new int[4]; // row 1 has 4 elements
jagged[2] = new int[1]; // row 2 has 1 element
AP Exam Tips
- •
- •
- •
- •
- •