Skip to content

Course navigation

For teachersTopic 4.11 · Lesson kit

2D Array Creation and Access

  • 3 class periods
  • 45 minutes each
  • Objective 4.11.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
3 class periods of 45 minutes
Learning objectives
4.11.A
Essential knowledge
4.11.A.14.11.A.24.11.A.34.11.A.44.11.A.54.11.A.6
Materials
Projector and the Grid Lock slide deckWhiteboard and markersMini whiteboards or scrap paper (grid sketches)IDE on the projector (demonstrations)Printed Grid Lock puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upthree workers, three arrays (slide 2)
  2. 0:05–0:2015 minDirect instructionan array of arrays and initializer lists (slides 3–7)
  3. 0:20–0:3212 minDirect instructiongrid[row][col] and swapped indices (slides 8–10)
  4. 0:32–0:419 minGuided practiceupdate the grid, then print (slide 11)
  5. 0:41–0:454 minClosurepoint to the box

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upwhat does new put in a 1D array?
  2. 0:05–0:1813 minDirect instructionnew and default values, the null box (slides 12–14)
  3. 0:18–0:2810 minDirect instructiongrid[r] is a shared row (slides 15–16)
  4. 0:28–0:357 minGuided practicetrace a row variable
  5. 0:35–0:427 minIndependent practiceworksheet questions 2 and 7 in class
  6. 0:42–0:453 minClosurecopy or the same row?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upthe last row and last column
  2. 0:05–0:1712 minDirect instructionlength for rows and columns, a length is never an index (slides 17–18)
  3. 0:17–0:247 minGuided practicevalid, or off the edge? (slide 19)
  4. 0:24–0:3410 minIndependent practiceworksheet questions 1 and 5 in pairs
  5. 0:34–0:384 minClosurevocabulary and one bracket or two (slides 20–21)
  6. 0:38–0:457 minExit ticket

Overview

This is the first 2D array lesson. Day 1 is the model and the syntax: a 2D array is an array of arrays, pictured as a grid of rows and columns (4.11.A.1); an initializer list of row lists creates one (4.11.A.3); and grid[row][col] reads or changes one element, row first (4.11.A.4). Day 2 is new type[rows][cols] and the default values it fills in (4.11.A.1, 4.11.A.2), then grid[r] as a whole row that is shared with the grid (4.11.A.5). Day 3 is grid.length for rows, grid[0].length for columns, and the valid index range (4.11.A.6).

Students know 1D arrays: creation with new and initializer lists, default values, indices, length, and ArrayIndexOutOfBoundsException (Topic 4.3). They also know that passing or assigning an array copies the reference, not the array (Topics 3.6 and 4.3). Lean on all of it: nearly every rule today is “the 1D rule, applied twice.”

Stay inside the topic boundary. No loops over a 2D array: visiting every element is Topic 4.12, and row-by-row or column-by-column algorithms are 4.13. Every example in this lesson names its indices directly. Every 2D array is rectangular; ragged arrays (rows of different lengths) are excluded from the course, so do not show one even as a curiosity.

Teacher note

The slides are the Grid Lock deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–11, Day 2 uses slides 12–16, and Day 3 uses slides 17–21. The Grid Lock puzzle worksheet (9 questions, about 30 minutes) needs Day 2 and Day 3 material, so it starts on Day 2: questions 2 and 7 in class and question 8 as homework after Day 2; questions 1 and 5 in class and questions 3, 4, 6, and 9 as homework after Day 3. There is no worksheet homework after Day 1.

Files whose names end in .snippet.java hold only the statements that go inside main. All files are in the topic’s examples/ folder. Running them is optional; the slides carry the examples.

  • Day 1 demonstrations: ReadScore, UpdateScore, WrongDimensions, SwappedIndices.
  • Day 2 demonstrations: NewDefaults, SeatChart, NullSeat, NullSeatFixed, RowAccess, RowAliasTrace, RowWrongType, RowToMethod.
  • Day 3 demonstrations: GridSize, BoardSize, MixedUpLength, PastLastColumn, BottomRight, TicketBooth.
  • Printed only (exit ticket): ExitGrid.

Day 1 · Warm-up: Three workers, three arrays

Show slide 2. Three workers each have a 1D array of hours for Monday to Wednesday. Ask the slide’s questions: with 30 workers, you would need 30 array variables and 30 names; and nothing so far puts the whole shop in one variable. Then ask what the three arrays look like stacked on top of each other: a table, one line per worker, one box per day. Name it: today that table becomes one variable, a 2D array.

Day 1 · Direct instruction: An array of arrays and initializer lists

  1. Goals (slide 3). Goals 1–3 are today, goal 4 is Day 2 (with the second half of goal 2, new), and goal 5 is Day 3.
  2. Two pictures (slides 4–5; 4.11.A.1). Show int[][] hours = { {6, 8, 5}, {7, 4, 9} }; as a grid with row and column labels, then as Java stores it: an outer array of two elements, each referring to a 1D row array. Say the rule from the slide: an outer array whose elements are 1D arrays, one per row. Point out that both row and column numbers start at 0, like every array index.
  3. Reading an initializer list (slide 6; 4.11.A.3). In Bus.java, count the inner lists (3, so 3 rows) and the values in each (2, so 2 columns). Size is always said rows first: a 3-by-2 array. Have students predict bus[2][0] and bus[0][1] before the reveal (Eve, Bo). Note that String[][] holds references: a 2D array can store primitives or objects (4.11.A.1).
  4. Two levels of braces need [][] (slide 7). int[] hours = { {6, 8, 5}, {7, 4, 9} }; does not compile: an int[] holds int values, and each inner list is a row, not an int. Demonstrate with WrongDimensions if the IDE is ready.

Misconception: A 2D array needs only one pair of brackets on the type

Students see two-level braces on the right and keep the int[] they used all of Topic 4.3. Teach them to count: the number of bracket pairs on the type must match the levels of braces in the list. The compiler message is illegal initializer for int (slide 7, WrongDimensions). Worksheet question 5, snippet 1, tests it.

Day 1 · Direct instruction: Grid[row][col] and swapped indices

  1. One box at a time (slides 8–9; 4.11.A.4). With hours from slide 9, the first index picks the row and the second picks the column. Cover the output and have students say hours[1][2] (9) and hours[0][1] (8). Then update the grid on the board line by line: hours[1][1] += 3 makes it 7, and hours[0][0] = hours[1][1] * 2 makes it 14. Compound assignment works on an element just as it does on a variable.
  2. Read grid[r][c] aloud as “row r, column c” every time, and ask students to do the same. On the AP exam, the first index is always the row.
  3. Swapped indices (slide 10). On the 3-by-3 lockers grid, the goal is row 2, column 0, but lockers[0][2] prints 13 instead of 31. Ask: “Did Java complain?” No: both indices are valid on a square grid, so the mistake is silent. The fix is lockers[2][0].

Misconception: The column comes first, like x and y on a graph

Students who know coordinates write grid[x][y], column first. On a square grid this runs and reads the wrong box; on a rectangular grid it can also throw an ArrayIndexOutOfBoundsException. Show SwappedIndices (Cy’s quiz 1 should be scores[2][1], 91, but scores[1][2] prints Ben’s 81). Fix the habit with words, not pictures: “row first, then column,” said aloud while writing. The worksheet’s Watch Out after question 2 repeats it.

Day 1 · Guided practice: Update the grid, then print

Show slide 11. Students draw p as a 3-by-2 grid on mini whiteboards and update it line by line. p[2][0] = p[0][1] + p[1][1] makes row 2, column 0 equal to 5 + 1, which is 6. p[1][0] -= 3 makes 8 into 5. The output is 6, then 7 (5 + 2). Check grids before outputs: a student with the right grid and a wrong output usually read a box by column first.

Teacher note

Insist on the drawn grid with row and column labels. It is the habit that makes Day 2’s shared-row trace and Day 3’s index checks easy. If time allows, run UpdateScore and have students predict all three lines first (80, 80, 20).

Day 1 · Closure: Point to the box

Write int[][] seat = { {1, 2, 3}, {4, 5, 6} }; on the board. Call out seat[1][0], seat[0][2], and seat[1][2]; students hold up the value on their fingers or whiteboards (4, 3, 6). Then ask how many rows and columns seat has, rows first: 2 by 3.

Day 2 · Warm-up: What does new put in a 1D array?

Ask students to write what new int[3], new boolean[3], and new String[3] hold right after they run (Topic 4.3): three 0s, three falses, three nulls. Ask: “If a 2D array is an array of arrays, what do you predict new int[2][3] holds?” Take a guess, then go to slide 13.

Day 2 · Direct instruction: New and default values

  1. new type[rows][cols] (slides 12–13; 4.11.A.1, 4.11.A.2). The first size is the rows, the second the columns. new int[2][4] makes 2 rows of 4. Every element gets the default for its type: 0 for int, 0.0 for double, false for boolean, null for any reference type such as String. Cover the output on slide 13 and have students fill it in (0, 0.0, false, null).
  2. The size is fixed (slide 13; 4.11.A.1). Once created, the number of rows and columns cannot change, just like a 1D array. To make a bigger grid, you create a new one.
  3. An empty String box holds null (slide 14). In Crew.java, crew[0][0].length() prints 3, but crew[1][2].length() throws a NullPointerException: new made the boxes, not any String objects. The fix checks != null before calling the method. Printing null with println is fine; only calling a method on it crashes. Demonstrate with NullSeat and NullSeatFixed.

Misconception: An unfilled String box holds the empty string

Students expect "", because a blank box looks empty. new puts null in every box of a reference-type grid, and calling length() or any other method on null throws a NullPointerException (Topic 1.14). Ask, for every reference grid, “Has anything been assigned to this box?” Worksheet question 7 is built on this mistake (claim 2 is the lie), and question 2’s choice C tests the opposite slip: giving a boolean grid the reference default.

Day 2 · Direct instruction: Grid[r] is a shared row

  1. One pair of brackets (slides 15–16; 4.11.A.5). hours[0] is a whole row, an int[]. Walk the type table on slide 16: hours is int[][], hours[0] is int[], hours[0][2] is int. Each pair of brackets peels off one level.
  2. It is shared, not copied. int[] mon = hours[0]; makes mon refer to row 0 itself, so mon[2] = 10 changes hours[0][2] to 10. Draw the arrow: mon and the outer array’s element 0 point to the same row. This is the same reference behavior as assigning one 1D array variable to another. mon.length is 3, the number of columns.
  3. A row is not an int. int x = hours[0]; does not compile (slide 16, bottom line; RowWrongType): the message is incompatible types: int[] cannot be converted to int.
  4. Optional: RowToMethod passes scores[0] to a method that takes an int[], so any 1D array method from Topic 4.3 can work on one row.

Misconception: A row variable is a copy of the row

Students think int[] mon = hours[0]; takes a snapshot, so changing mon leaves the grid alone. Draw the reference arrow from the slide 5 picture: there is one row object and two ways to reach it. Worksheet question 3 depends on this (row[0] = row[1] * 2 changes pad[2][0]), and so does the exit ticket’s question 1.

Misconception: One pair of brackets gives one value

grid[1] looks like an index, so students store it in an int. Have them say the type of each expression by counting bracket pairs: none is the grid, one is a row, two is one value. Worksheet question 5, snippet 2, and slide 21’s sentence starter both practice it.

Day 2 · Guided practice: Trace a row variable

Write RowAliasTrace on the board (or run it after students predict). stock is { {5, 0, 3}, {2, 8, 6} }, top is stock[0]. Students draw the grid, draw top’s arrow to row 0, and update: top[1] = 4 changes stock[0][1] to 4; stock[0][2] += top[0] adds 5 to 3, giving 8. The output is 4, 8, and 3 (stock[1].length, the number of columns). Ask which line changed the grid through top, and how top[2] “knew” about a change made through stock.

Day 2 independent practice and closure

Students work worksheet questions 2 and 7 in class (about seven minutes): the JVM trace with new double[2][3] and new boolean[2][3] (answer A, 4.5 false), and two truths and a lie about an unfilled String grid. Question 8 is homework: a new String[3][2] grid where one column index is 2. Students know from Topic 4.3 that index 2 is off the end of a length-2 array; tomorrow names the rule for 2D arrays.

For closure, ask: “After int[] a = g[1]; and a[0] = 9;, what is g[1][0]?” (9, because a is the same row.)

Day 3 · Warm-up: The last row and last column

Read the worksheet’s Think First aloud: a grid has 3 rows and 5 columns. What is the index of its last row, and of its last column? Students write both (2 and 4) and how they knew. Collect the reasoning “one less than the count” and move to slide 17 to find the counts in code.

Day 3 · Direct instruction: Length for rows and columns

  1. length gives rows and columns (slide 17; 4.11.A.6). For plot = new int[4][6], plot.length is 4, the number of rows, because the outer array has 4 elements. plot[0].length is 6, the length of one row, which is the number of columns. Walk the slide’s table, including plot.length - 1 (3) and plot[0].length - 1 (5) for the last row and column, then the output (4, 6, 8).
  2. Answer the question students will ask: why row 0? Every row has the same length in this course, so any row works, and row 0 always exists in a grid with at least one row. The worksheet’s Fair Question after question 4 says the same.
  3. A length is never a valid index (slide 18; 4.11.A.6). plot[0][plot[0].length] asks for column 6 of a row with columns 0–5 and throws ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6. Valid row indices are 0 to grid.length - 1; valid column indices are 0 to grid[0].length - 1. Demonstrate with PastLastColumn, then BottomRight, which makes the mistake twice.

Misconception: grid.length is the number of columns

Students read “length” as width, or reuse grid.length because it is the only length they remember. On a square grid the slip is invisible; on a 3-by-4 grid, scores[0][scores.length - 1] quietly reads column 2 instead of column 3 (MixedUpLength). Make the rule a two-line chant: rows from grid.length, columns from grid[0].length. Worksheet questions 4 and 6 drill it, and question 6’s last line names the hidden-on-a-square-grid danger.

Misconception: The length is the last index

The 1D off-by-one from Topic 4.3 comes back twice as often, once for rows and once for columns. Ask “what is the count, and what is the last index?” as two separate questions for each dimension. Slide 18, worksheet question 1 (g[3][0]), question 3’s decoy tile (pad[pad.length]), and question 8 all hinge on it.

Day 3 · Guided practice: Valid, or off the edge?

Show slide 19 with double[][] rain = new double[4][6]. Rows are 0–3 and columns are 0–5. Students mark each expression on mini whiteboards: rain[3][5] is valid (the bottom-right box, holding 0.0); rain[4][0] crashes (row 4 does not exist); rain[0][6] crashes (column 6 does not exist); rain[5][3] crashes (row 5 does not exist). rain[2] is valid and has type double[], a whole row of 6 values. Ask which crash a student who swapped the indices would have avoided by luck, and why that is not a fix.

Day 3 · Independent practice: Independent practice

In pairs, students work worksheet questions 1 and 5 (about ten minutes): the pencil check on g (values, both lengths, and one crash) and you’re the compiler (six snippets covering bracket pairs, defaults, g[1, 0], and a row’s length). Circulate on question 5, snippet 4: g[1, 0] is not Java; each index needs its own brackets.

The rest of the worksheet is homework: questions 3, 4, 6, and 9 (code tiles with a shared row, the snippet pool on the menu grid, the face-off between grid.length and grid[0].length, and who am I). Students check question 8 from last night against today’s rule.

Day 3 · Closure: Closure and exit ticket

Show slide 20 (vocabulary) briefly, then slide 21: partners explain what hours, hours[1], and hours[1][2] each give, using the sentence starter “No brackets gives the grid, one pair gives a row, and two pairs give one value.” Then give the exit ticket (about seven minutes). Question 1 checks new, defaults, a shared row, and length (4.11.A.2, 4.11.A.5, 4.11.A.6); question 2 checks reading an initializer list and [row][col] (4.11.A.3, 4.11.A.4); question 3 checks creating a grid with new, its defaults, and the valid row range (4.11.A.1, 4.11.A.2, 4.11.A.6). Re-teach the weakest one at the start of Topic 4.12, where students will need every one of these to traverse a grid.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[][] t = new int[3][4];
t[2][1] = 5;
int[] r = t[2];
r[3] = r[1] + t.length;
System.out.println(t[2][3]);
System.out.println(t[0].length);
System.out.println(t[1][1]);
  1. 0, then 4, then 0, each on its own line
  2. 8, then 4, then 0, each on its own line
  3. 9, then 4, then 0, each on its own line
  4. 8, then 3, then 0, each on its own line
Check your reasoning

B. new int[3][4] makes 3 rows of 4 columns, all 0. Line 2 sets t[2][1] to 5. r refers to row 2 itself, not a copy, so r[1] is 5, and t.length is 3 (the rows), making r[3] and therefore t[2][3] equal to 8. t[0].length is the number of columns, 4. t[1][1] was never assigned, so it still holds the default 0.

A treats r as a copy of row 2, but r and t[2] refer to the same row, so changing r[3] changes t[2][3]. C uses t.length as the number of columns (4), but t.length counts the rows, 3. D mixes up the two lengths the other way: t[0].length is the length of one row, which is the number of columns, 4.

Question 2 · Multiple choice

A program creates String[][] shelf = { {"pen", "cup", "map"}, {"jar", "box", "fan"} };. Which expression evaluates to "fan"?

  1. shelf[2][3]
  2. shelf[1][shelf.length - 1]
  3. shelf[1][2]
  4. shelf[2][1]
Check your reasoning

C. shelf has 2 rows (two inner lists) of 3 columns. "fan" is in row 1, column 2, and the row index comes first. A counts from 1 instead of 0: row 2 and column 3 do not exist, so it throws an ArrayIndexOutOfBoundsException. B uses shelf.length (2, the rows) for the column, so it reads shelf[1][1], "box"; the last column is shelf[0].length - 1. D swaps the indices, column first; row 2 does not exist, so it throws an ArrayIndexOutOfBoundsException.

Question 3 · Multiple choice

A program needs a double 2D array named temps for 7 days (rows) of 24 hours (columns). Which statement is correct?

  1. double[][] temps = new double[24][7]; creates it, and right after, temps[6][23] holds 0.0.
  2. double[][] temps = new double[7][24]; creates it, and right after, temps[6][23] holds null.
  3. double[][] temps = new double[7][24]; creates it, and temps[7][0] is a valid element, because there are 7 rows.
  4. double[][] temps = new double[7][24]; creates it, temps[6][23] starts as 0.0, and temps[7][0] throws an ArrayIndexOutOfBoundsException.
Check your reasoning

D. The number of rows comes first after new, then the number of columns. new fills every element with the default for double, 0.0. temps.length is 7, so the row indices are 0 through 6, and row 7 throws an ArrayIndexOutOfBoundsException.

A puts the columns first; that array has 24 rows of 7 columns, so temps[6][23] throws an ArrayIndexOutOfBoundsException. B uses the default for reference types; a double element starts at 0.0. C mixes up the number of rows with the last row index, which is one less, 6.