ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.11

2D Array Creation and Access

Skill 2.BSkill 3.B

Big idea: A 2D array is an array of rows, where each row is itself an array. Always index row first, then column.

Learning objectives
  • Develop code used to represent collections of related data using two-dimensional (2D) array objects.

Creating a grid

Code
int[][] g = new int[3][4];     // 3 rows, 4 columns, all 0
int[][] m = { {1, 2, 3},
              {4, 5, 6} };
System.out.println(g.length + " " + g[0].length);
System.out.println(m.length + " " + m[0].length);
System.out.println(m[1][2]);
Output
3 4
2 3
6

Rows are arrays

m[r] is a whole row, a 1D array. m.length is the number of rows and m[0].length the number of columns.

col 0col 1col 2
row 0m[0][0] = 1m[0][1] = 2m[0][2] = 3
row 1m[1][0] = 4m[1][1] = 5m[1][2] = 6
Code
int[][] m = { {1, 2, 3}, {4, 5, 6} };
int[] row = m[1];
row[0] = 40;
System.out.println(m[1][0]);
Output
40
Key points
  • A 2D array is an array of arrays, fixed in size at creation.
  • new fills elements with defaults.
  • Access with [row][col]; g[r] is a whole row.
  • g.length = rows; g[0].length = columns.
Watch out
  • new int[3][4] means 3 rows and 4 columns.
Quick check
For String[][] seats = new String[5][8]; what is seats[4][7] and what is seats.length?
Show answer
null (the last seat) and 5 (rows).
Not on the exam
  • Nonrectangular (jagged) 2D arrays.