By LearnAllStudents Editorial Team. Source check dates are listed below.
Official resources
Add row totals on a non-square grid
For {{2, 3, 4}, {8, 1, 2}}, row 0 sums to 9 and row 1 sums to 11. Start the running total at zero for each row. A single running total outside the outer loop would incorrectly make the second total 20.
Use the length of the current row
static int bestRow(int[][] grid) {
int best = -1;
int bestTotal = Integer.MIN_VALUE;
for (int row = 0; row < grid.length; row++) {
int total = 0;
for (int col = 0; col < grid[row].length; col++) {
total += grid[row][col];
}
if (best == -1 || total > bestTotal) {
best = row;
bestTotal = total;
}
}
return best;
}The example returns −1 for an empty outer array and assumes each row is non-null and its sum fits an int. Because it updates only for a strictly greater total after choosing a first row, equal totals retain the earlier row.
Use shapes that expose indexing mistakes
- Test two rows with three columns to detect a reused bound.
- Test row totals of −10 and −3 to check the initial maximum.
- Test two equal totals to confirm what happens when the prompt specifies a tie rule.
Try it yourself
Trace bestRow for {{−6, 1}, {−2, −3}, {−4, 0}}. Which row wins if you remove the last row? What changes if the second comparison uses >=?
Check your reasoning
The totals are −5, −5 and −4, so index 2 wins. With just the first two rows, index 0 wins under >. Under >= the later tied row replaces it, so index 1 wins.
How a tutor would approach this
Describe the return value precisely. Write whether the method returns a value, a count, a row index or a column index. Use that label in your trace table.
Frequently asked questions
Which index comes first?
In grid[row][col], the first index selects a row array and the second selects an element within it.
Why can a square grid hide a bug?
The row count and column count agree, so swapping bounds may not produce an error.
Where should I reset a row total?
Reset it in the outer loop before processing the next row’s columns.
Can I assume the same tie rule on every prompt?
Use the rule stated in the question. The example deliberately keeps the first tied row.
Official sources
- College Board AP Computer Science A exam and Java Quick Reference (checked 2026-11-26)
- College Board AP Computer Science A sample questions (checked 2026-11-26)
Related pages
Try a free 30-minute demo
Work through a question with a tutor. No payment needed.
Request a free 30-minute demo