Two-Dimensional Arrays
AP Computer Science A · Unit 4 — Data Collections
An array of arrays
In Java a 2D array is really an array whose elements are arrays. For int[][] g = new int[3][4];:
g.length → 3 number of ROWS g[0].length → 4 number of COLUMNS in row 0 g[r][c] → element at row r, column c
The first index is always the row. On the AP exam all 2D arrays are rectangular, so every row has the same length and g[0].length is a safe column count — but writing g[r].length in the inner loop is always correct and costs nothing.
Row-major traversal
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
System.out.print(g[r][c]);
}
}
for (int[] row : g) { // each row is an int[]
for (int v : row) { // each v is an int
System.out.print(v);
}
}Swapping the two loop headers gives column-major order, which visits the same cells in a different order — the difference matters as soon as you print, or stop early.
g[r][2]. Writing g[2][c] by mistake adds up row 2 — both results are valid numbers, so nothing tells us we took the wrong one.Worked example: sum of each column
Write a method that returns a one-dimensional array containing the sum of each column of the rectangular two-dimensional array int[][] g.
Solution
public static int[] tongCot(int[][] g) {
int[] kq = new int[g[0].length]; // length equals the NUMBER OF COLUMNS
for (int c = 0; c < g[0].length; c++) {
for (int r = 0; r < g.length; r++) {
kq[c] += g[r][c];
}
}
return kq;
}Three places to go wrong, handled one by one. One: the length of the result array is the number of columns g[0].length, not the number of rows — there are as many sums as there are columns. Two: inside, it must be g[r][c], keeping the row-column order even though the outer loop is running over columns. Three: a newly created kq is already filled with 0, so accumulating straight into it is safe, with no initializing assignment needed.
With {{1,2,3},{4,5,6},{7,8,9}} the method returns {12, 15, 18}.
Common mistake
The deadly trap of two-dimensional arrays is swapping the two indexes: writingg[c][r] instead of g[r][c]. With a square array it runs smoothly and returns a number that looks perfectly reasonable, so no one notices until grading. How to prevent it: name the loop variables r and c rather than using i and j — your eye will see g[c][r] as wrong immediately, but not g[j][i]. The second trap: using g.length as the number of columns. Remember one sentence — g.length counts rows; you need one more pair of square brackets to get the columns.Key takeaway
The first index is the row,g.length is the number of rows, g[0].length is the number of columns. Row-major traversal is the default; swapping the two loops changes the order of visiting, not the set of cells visited.