| Study Guides
College Board · cb-cs-a · AP Computer Science A · 2D Arrays · 16 min read · Updated 2026-05-07

2D Arrays — AP Computer Science A CS A Study Guide

For: AP Computer Science A candidates sitting AP Computer Science A.

Covers: 2D array declaration syntax, row-major traversal, common 2D array operations (sum, search, reflection), boundary condition handling, and real-world use cases including game boards and linear algebra matrices.

You should already know: Basic Java or any other procedural-language programming.

A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers and may differ in wording, numerical values, or context. Use them to practise the technique; cross-check with official College Board mark schemes for grading conventions.


1. What Is 2D Arrays?

A 2D (2-dimensional) array is a nested array structure that stores data in a grid of rows and columns, analogous to a spreadsheet, tic-tac-toe board, or mathematical matrix. In Java, a 2D array is implemented as an array of 1D arrays, where each top-level element represents one full row of the grid. Common synonyms for 2D arrays include grids, matrices, and 2D lists (the term used in Python and other non-Java languages). This topic is covered in Unit 8 of the AP CS A Course and Exam Description, accounts for 7-10% of the multiple-choice section, and appears in at least one free-response question (FRQ) on nearly every exam.

2. 2D array declaration

In Java, 2D arrays are defined with two dimensions: the number of rows first, followed by the number of columns per row. All elements in a 2D array must be of the same data type (e.g. int, String, boolean).

There are two primary declaration formats tested on the AP exam:

  1. Fixed-size declaration: Used when you know the dimensions of the grid but not the initial values. The array is automatically initialized with default values (0 for numeric types, false for booleans, null for reference types).
// Creates a 3-row, 4-column grid of integers to store test scores for 3 students, 4 assignments each
int[][] scores = new int[3][4];
  1. Initializer list declaration: Used when you know the exact values of the grid at declaration time. Each inner set of curly braces represents one row of the array.
int[][] scores = {{85, 92, 78, 90}, {76, 81, 94, 89}, {98, 87, 91, 83}};

To access an individual element, use the syntax arrayName[rowIndex][columnIndex], where indices are zero-indexed. For the example above, scores[1][2] returns 94: this is the 2nd row (index 1) and 3rd column (index 2) of the grid.

AP exam note: Jagged arrays (2D arrays where rows have different column counts) are allowed in Java and may appear in multiple-choice questions, but 95% of FRQs use rectangular 2D arrays where all rows have the same number of columns.

3. Row-major traversal

Row-major traversal is the standard, most efficient way to iterate through all elements of a 2D array in Java. In this traversal order, you visit every element in a single row before moving to the next row. This is the traversal method tested on the vast majority of AP CS A 2D array questions, as it aligns with Java's internal storage of 2D arrays as arrays of rows.

The standard nested loop structure for row-major traversal is:

// Outer loop iterates over all rows
for (int row = 0; row < scores.length; row++) {
 // Inner loop iterates over all columns in the current row
 for (int col = 0; col < scores[row].length; col++) {
 // Access element at scores[row][col]
 System.out.print(scores[row][col] + " ");
 }
 System.out.println(); // Print new line after each row
}

For the scores array above, this code will print each row of scores on its own line, as expected.

You can also use enhanced for (for-each) loops for row-major traversal if you do not need the index values for modification or calculation:

for (int[] row : scores) { // Each top-level element is a row (1D int array)
 for (int score : row) { // Each element of the row array is a single score value
 System.out.print(score + " ");
 }
 System.out.println();
}

Exam tip: Examiners frequently test your ability to distinguish row-major traversal from column-major traversal (where you visit all elements in a column before moving to the next column). If you see loops where the column index is in the outer loop, you are looking at column-major order.

4. Common patterns — sum, search, reflection

Three of the most frequently tested 2D array operations on the AP exam are sum calculation, value search, and grid reflection.

Sum calculation

The total sum of all elements in a 2D array is calculated by adding every element in the grid, regardless of traversal order. The mathematical formula for the sum of a rectangular 2D array with R rows and C columns is: $$ \text{Total Sum} = \sum_{r=0}^{R-1} \sum_{c=0}^{C-1} arr[r][c] $$

Worked example code for sum calculation:

int total = 0;
for (int r = 0; r < scores.length; r++) {
 for (int c = 0; c < scores[r].length; c++) {
 total += scores[r][c];
 }
}
// For the sample scores array, total will equal 85+92+78+90+76+81+94+89+98+87+91+83 = 1044

Value search

A search operation looks for a target value in the 2D array and returns either its coordinates or a boolean indicating if the value exists. Worked example code for a search that returns coordinates:

// Returns [row, column] of target, or [-1, -1] if target not found
public static int[] search(int[][] arr, int target) {
 for (int r = 0; r < arr.length; r++) {
 for (int c = 0; c < arr[r].length; c++) {
 if (arr[r][c] == target) {
 return new int[]{r, c};
 }
 }
 }
 return new int[]{-1, -1};
}
// For the sample scores array, search(scores, 94) returns [1, 2]

Grid reflection

Reflection operations flip a grid horizontally (left to right) or vertically (top to bottom). For horizontal reflection, you swap elements at column c and column cols - 1 - c for each row, up to the midpoint of the row to avoid double-swapping. Worked example code for horizontal reflection:

public static void reflectHorizontal(int[][] grid) {
 int cols = grid[0].length;
 for (int r = 0; r < grid.length; r++) {
 // Only loop to midpoint to avoid swapping pairs twice
 for (int c = 0; c < cols / 2; c++) {
 int temp = grid[r][c];
 grid[r][c] = grid[r][cols - 1 - c];
 grid[r][cols - 1 - c] = temp;
 }
 }
}
// For a grid {{1,2,3}, {4,5,6}}, this method returns {{3,2,1}, {6,5,4}}

5. Boundary conditions

Boundary conditions are rules that prevent you from accessing array indices outside the valid range, which would throw an ArrayIndexOutOfBoundsException — a common error that costs points on FRQs. For a 2D array with R rows and C columns, valid indices are:

  • Row indices: 0 ≤ r ≤ R-1
  • Column indices: 0 ≤ c ≤ C-1

Boundary checks are required whenever you access adjacent cells (e.g. checking neighboring cells in a Minesweeper game) or traverse only edge elements of the grid. A reusable validity check method is:

public static boolean isValid(int[][] arr, int r, int c) {
 return r >= 0 && r < arr.length && c >= 0 && c < arr[0].length;
}

Worked example: Counting edge elements of a grid. Edge elements are cells where the row is 0 or R-1, or the column is 0 or C-1.

public static int countEdgeElements(int[][] arr) {
 int count = 0;
 int rows = arr.length;
 int cols = arr[0].length;
 for (int r = 0; r < rows; r++) {
 for (int c = 0; c < cols; c++) {
 if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
 count++;
 }
 }
 }
 return count;
}
// For a 3x4 grid, this method returns 10 (4 top edge, 4 bottom edge, 1 left middle, 1 right middle)

6. Real-world examples — game boards, matrices

2D arrays are one of the most widely used data structures in practical programming, with two common use cases tested frequently on the AP exam:

Game boards

Nearly all grid-based games (Tic Tac Toe, Chess, Minesweeper, 2D tile games) use 2D arrays to store the state of the game board. For example, a Tic Tac Toe board is a 3x3 2D array of char values, where each cell stores 'X', 'O', or ' ' (empty). To check for a win, you traverse rows, columns, and diagonals to see if all cells match a player's symbol.

Linear algebra matrices

2D arrays are the standard representation of mathematical matrices, used for operations like addition, multiplication, and transposition in computer graphics, machine learning, and physics simulations. The formula for matrix addition (for two matrices of identical dimensions) is: $$ (A + B)[r][c] = A[r][c] + B[r][c] $$ Worked example code for matrix addition:

public static int[][] addMatrices(int[][] a, int[][] b) {
 int rows = a.length;
 int cols = a[0].length;
 int[][] result = new int[rows][cols];
 for (int r = 0; r < rows; r++) {
 for (int c = 0; c < cols; c++) {
 result[r][c] = a[r][c] + b[r][c];
 }
 }
 return result;
}

7. Common Pitfalls (and how to avoid them)

  • Wrong move: Swapping row and column indices when accessing elements (e.g. scores[col][row] instead of scores[row][col]). Why students do it: Confusion with Cartesian (x,y) coordinates where the horizontal axis is listed first. Correct move: Always test with a small 2x2 grid to confirm you are accessing the expected value before writing full code.
  • Wrong move: Using arr.length to get the number of columns instead of arr[0].length for rectangular arrays. Why students do it: Forgetting that arr.length returns the number of rows (since a 2D array is an array of rows). Correct move: Use arr.length for row count, and arr[row].length for column count (works for both rectangular and jagged arrays).
  • Wrong move: Traversing all columns/rows during reflection operations, leading to swapping pairs of elements back to their original positions. Why students do it: Forgetting that each swap affects two elements, so you only need to iterate up to the midpoint of the row/column. Correct move: Loop the inner index from 0 to length/2 (exclusive) for all reflection operations.
  • Wrong move: Skipping boundary checks when accessing adjacent cells, leading to ArrayIndexOutOfBoundsException. Why students do it: Assuming all cells have four neighbors, which is not true for edge and corner cells. Correct move: Always call a validity check method before accessing any adjacent cell, even if the question implies the input is a valid cell.
  • Wrong move: Using enhanced for loops to modify primitive values in a 2D array. Why students do it: Confusion with how primitive types are passed in Java: the loop variable is a copy of the element, not a reference to the array value. Correct move: Use standard indexed for loops if you need to modify array values; use enhanced for loops only for reading values or modifying reference-type elements (e.g. objects).

8. Practice Questions (AP Computer Science A Style)

Question 1 (Multiple Choice)

Given the following code snippet, what is the value of sum after execution?

int[][] arr = {{2, 4, 6}, {1, 3, 5}, {7, 8, 9}};
int sum = 0;
for (int c = 0; c < arr[0].length; c++) {
 for (int r = 0; r < arr.length; r++) {
 sum += arr[r][c];
 }
}

A) 45 B) 36 C) 27 D) 18

Worked Solution: The loops use column-major traversal, but the sum of all elements in a grid is identical regardless of traversal order. The total sum of all elements is 2+4+6+1+3+5+7+8+9 = 45. The correct answer is A. Common trap: Students waste time calculating column sums instead of recognizing that total sum is independent of traversal order.


Question 2 (FRQ Part A)

Write a method public static int countDivisibleBy3(int[][] grid) that returns the number of elements in the rectangular 2D array grid that are divisible by 3. Assume grid is not null and has at least one element.

Worked Solution:

public static int countDivisibleBy3(int[][] grid) {
 int count = 0;
 // Row-major traversal of all elements
 for (int r = 0; r < grid.length; r++) {
 for (int c = 0; c < grid[r].length; c++) {
 // Check if element is divisible by 3 (remainder 0 when divided by 3)
 if (grid[r][c] % 3 == 0) {
 count++;
 }
 }
 }
 return count;
}

Grading breakdown: 1 point for correct nested loop structure, 1 point for correct divisibility check, 1 point for correct counter increment and return. For the sample array in Question 1, this method returns 3 (values 6, 3, 9).


Question 3 (FRQ Part B)

Write a method public static void reflectVertical(int[][] grid) that flips the rectangular 2D array grid vertically (top to bottom). For example, if grid is {{1,2},{3,4},{5,6}}, after reflection it becomes {{5,6},{3,4},{1,2}}.

Worked Solution:

public static void reflectVertical(int[][] grid) {
 int rows = grid.length;
 // Swap row r with row (rows - 1 - r) up to midpoint of rows
 for (int r = 0; r < rows / 2; r++) {
 // Swap entire row arrays (no need to swap individual elements)
 int[] temp = grid[r];
 grid[r] = grid[rows - 1 - r];
 grid[rows - 1 - r] = temp;
 }
}

Grading breakdown: 1 point for correct loop structure up to row midpoint, 1 point for correct row index calculation, 1 point for correct row swap.

9. Quick Reference Cheatsheet

Concept Syntax / Rule
Fixed-size 2D array declaration type[][] name = new type[numRows][numCols];
Initializer list declaration type[][] name = {{row1val1, row1val2}, {row2val1, row2val2}};
Element access name[rowIndex][colIndex] (indices start at 0)
Row-major traversal Outer loop over rows, inner loop over columns: for (int r=0; r<arr.length; r++) { for (int c=0; c<arr[r].length; c++) { ... } }
Index validity check r >= 0 && r < arr.length && c >= 0 && c < arr[r].length
Horizontal reflection Swap arr[r][c] and arr[r][cols-1-c] for c < cols/2
Vertical reflection Swap arr[r] and arr[rows-1-r] for r < rows/2
Common error fix ArrayIndexOutOfBoundsException is caused by accessing indices outside the 0 to length-1 range; add boundary checks to resolve.

10. What's Next

2D arrays are a foundational data structure that connects directly to later AP CS A topics including ArrayLists of ArrayLists, recursion on grids, and the mandatory 2D array FRQ that appears on nearly every AP CS A exam. Mastery of 2D array traversal and operations is also a prerequisite for advanced programming topics outside the syllabus, including game development, machine learning model training, and 3D computer graphics rendering.

If you have any questions about 2D array syntax, common patterns, or practice problems, you can ask Ollie, our AI tutor, at any time for personalized explanations and extra practice tailored to your weak areas. You can also find more AP CS A study materials, full practice exams, and topic-specific quizzes on the homepage to prepare for your exam.

← Back to topic

Stuck on a specific question?
Snap a photo or paste your problem — Ollie (our AI tutor) walks through it step-by-step with diagrams.
Try Ollie free →