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
- 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. - 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. - 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 predictbus[2][0]andbus[0][1]before the reveal (Eve,Bo). Note thatString[][]holds references: a 2D array can store primitives or objects (4.11.A.1). - Two levels of braces need
[][](slide 7).int[] hours = { {6, 8, 5}, {7, 4, 9} };does not compile: anint[]holdsintvalues, and each inner list is a row, not anint. Demonstrate withWrongDimensionsif 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
- One box at a time (slides 8–9; 4.11.A.4). With
hoursfrom slide 9, the first index picks the row and the second picks the column. Cover the output and have students sayhours[1][2](9) andhours[0][1](8). Then update the grid on the board line by line:hours[1][1] += 3makes it 7, andhours[0][0] = hours[1][1] * 2makes it 14. Compound assignment works on an element just as it does on a variable. - 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. - Swapped indices (slide 10). On the 3-by-3
lockersgrid, the goal is row 2, column 0, butlockers[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 islockers[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
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:0forint,0.0fordouble,falseforboolean,nullfor any reference type such asString. Cover the output on slide 13 and have students fill it in (0, 0.0, false, null).- 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.
- An empty String box holds null (slide 14). In
Crew.java,crew[0][0].length()prints 3, butcrew[1][2].length()throws aNullPointerException:newmade the boxes, not anyStringobjects. The fix checks!= nullbefore calling the method. Printingnullwithprintlnis fine; only calling a method on it crashes. Demonstrate withNullSeatandNullSeatFixed.
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
- One pair of brackets (slides 15–16; 4.11.A.5).
hours[0]is a whole row, anint[]. Walk the type table on slide 16:hoursisint[][],hours[0]isint[],hours[0][2]isint. Each pair of brackets peels off one level. - It is shared, not copied.
int[] mon = hours[0];makesmonrefer to row 0 itself, somon[2] = 10changeshours[0][2]to 10. Draw the arrow:monand 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.lengthis 3, the number of columns. - A row is not an int.
int x = hours[0];does not compile (slide 16, bottom line;RowWrongType): the message isincompatible types: int[] cannot be converted to int. - Optional:
RowToMethodpassesscores[0]to a method that takes anint[], 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
- length gives rows and columns (slide 17; 4.11.A.6). For
plot = new int[4][6],plot.lengthis 4, the number of rows, because the outer array has 4 elements.plot[0].lengthis 6, the length of one row, which is the number of columns. Walk the slide’s table, includingplot.length - 1(3) andplot[0].length - 1(5) for the last row and column, then the output (4, 6, 8). - 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.
- 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 throwsArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6. Valid row indices are 0 togrid.length - 1; valid column indices are 0 togrid[0].length - 1. Demonstrate withPastLastColumn, thenBottomRight, 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.