AP Computer Science A — Unit 8 Review: Two‑Dimensional Arrays


1. Declaring & Initializing 2D Arrays

▶️ Fixed‑size Declaration

int[][] a = new int[3][4];

▶️ Literal Initialization

int[][] b = {
  {2,3,1},
  {8,5,6}
};

2. Underlying Memory Model

text heap: [row0Ref, row1Ref, row2Ref] row0Ref ──▶ [ , , , ] row1Ref ──▶ [ , , , ] row2Ref ──▶ [ , , , ] * Outer array holds references to inner 1D arrays. * Inner arrays hold actual elements.


3. Accessing & Assigning Elements

System.out.println(b[0][1]);  // row 0, col 1
a[1][2] = 9;                   // set row 1, col 2
boolean check = (a[2][0] < b[1][1]);

4. Traversal with Nested Loops

▶️ Traditional for Loops (row‑major order)

for (int r = 0; r < arr.length; r++) {
    for (int c = 0; c < arr[r].length; c++) {
        System.out.print(arr[r][c] + " ");
    }
    System.out.println();
}

▶️ Enhanced for Loops

for (int[] row : arr) {
    for (int val : row) {
        System.out.print(val + " ");
    }
    System.out.println();
}

5. Common Algorithms

▶️ Double All Elements

for (int r = 0; r < arr.length; r++)
  for (int c = 0; c < arr[r].length; c++)
    arr[r][c] *= 2;

▶️ Reverse Each Row (In‑place)

for (int r = 0; r < arr.length; r++) {
  int cols = arr[r].length;
  for (int c = 0; c < cols/2; c++) {
    int temp = arr[r][c];
    arr[r][c] = arr[r][cols-1-c];
    arr[r][cols-1-c] = temp;
  }
}

6. Temple of Arrays FRQ Pattern

Given a 2D String[][] floor, implement:

  1. lineOfIdentical(String[] row)boolean:

  2. Return true if all entries in row are equal.

  3. isFloorSafe(String[][] floor)boolean:

  4. No entries equal to "X" or "Y".

  5. Not all entries are identical.
  6. canCrossFloor(String[][] floor)boolean:

  7. isFloorSafe(floor) == true and

  8. At least one row satisfies lineOfIdentical(...).

Traversal tip: Use for loops over floor.length (rows) and floor[r].length (cols).


7. Key Takeaways


Master these patterns to ace AP CSA questions on two‑dimensional arrays!