2D arrays

AP Computer Science A · Unit 4: Data structures

2D arrays notes

Fact-checked by a second, independent AI review.

Understand how 2D arrays work in Java: arrays of arrays, how to declare, initialize, traverse, and use their lengths in exams.

Declaration & creation
Declare as type[][] name and initialize with new Type[rows][cols] or as an array of arrays.
Access & indices
Access elements with name[row][col]. Use name.length for rows and name[row].length for columns (handles jagged arrays).
Traversal
Use nested loops to visit every element; inner loop runs over columns, outer over rows.
Initialization & default values
2D arrays are filled with default values (0 for int, false for boolean, null for objects) unless initialized.
Rectangular vs jagged
Rectangular: all rows have same length; jagged: rows can have different lengths (name[i].length varies).
Common exam tasks
Compute sums, find min/max, search for a value, or print a matrix; be ready to flatten or transpose in simple cases.

Remember it: Think of a 2D array as a spreadsheet: rows are horizontal, columns vertical, and you index by [row][col].

Exam tip: Markers look for correct use of .length for row count and column count, proper nested loops, handling of jagged arrays, and clear method/parameter usage when passing 2D arrays.

Syllabus checklist

  • 2D arrays: core ideas
  • Terms and typical exam questions for "Data structures" in AP Computer Science A (Java
  • College Board)

Practice questions

  1. 1. Which loop nests correctly traverse all elements of a 2D array a with rows and cols?

    Answer checked

    Show answer

    Answer: for (int i=0; i<a.length; i++) for (int j=0; j<a[i].length; j++. The correct pattern uses a.length for rows and a[i].length for columns; this ensures correct lengths per row.

  2. 2. A 2D array is accessed as a[row][col].

    Answer checked

    Show answer

    Answer: True. In Java, two indices access a specific element: first the row, then the column.

  3. 3. In Java, a 2D array is accessed with ____ brackets.

    Answer checked

    Show answer

    Answer: two-dimensional. Java uses two-dimensional brackets to denote a 2D array, e.g., int[][] arr.

  4. 4. Given int[][] a = {{1,2,3},{4,5,6}}; what is the sum of row 1 (0-based)?

    Answer checked

    Show answer

    Answer: 15. Row 1 is {4,5,6}; sum is 4+5+6 = 15.

  5. 5. What is arr[1][2] for int[][] arr = {{5,6,7},{8,9,10}}?

    Answer checked

    Show answer

    Answer: 10. arr[1][2] refers to row 1, column 2, which is 10.

Practise 2d arrays as a game

Hearts, combos, streaks and an AI tutor that explains every answer. Start free.

Start free

More from Unit 4: Data structures