Skip to content

Course navigation

For teachersTopic 4.3 · Lesson kit

Array Creation and Access

  • 3 class periods
  • 45 minutes each
  • Objective 4.3.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.3.A
Essential knowledge
4.3.A.14.3.A.24.3.A.34.3.A.44.3.A.54.3.A.6
Materials
Projector and the Mind the Index slide deckWhiteboard and markersMini whiteboards or scrap paperIDE on every computer (Day 2)Printed Mind the Index puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upfive quizzes, five variables (slide 2)
  2. 0:05–0:1510 minDirect instructionwhat an array is, element types (slides 3–6)
  3. 0:15–0:2510 minDirect instructionsquare brackets and an index (slides 7–9)
  4. 0:25–0:305 minActivityDay 1 pause and try — trace the cost array (slide 10)
  5. 0:30–0:4212 minDirect instructiondefault values and initializer lists (slides 11–13)
  6. 0:42–0:453 minClosurewhich index is quiz 1?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upwhat does new put in each element?
  2. 0:05–0:1510 minDirect instructionthe length attribute, length is fixed (slides 14–16)
  3. 0:15–0:238 minDirect instructionone past the end (slides 17–18)
  4. 0:23–0:4017 minGuided practicebe the compiler, then check in the IDE (worksheet question 3)
  5. 0:40–0:455 minClosurethe last index of any array

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Independent practice
  • Closure
  • Exit ticket
  • Activity
  1. 0:00–0:055 minWarm-upis arr[-1] the last element?
  2. 0:05–0:1510 minDirect instructionarrays of object references (slide 19)
  3. 0:15–0:205 minActivityDay 3 pause and try — elements are Strings (slide 20)
  4. 0:20–0:3212 minIndependent practicepuzzle worksheet questions 7–9
  5. 0:32–0:375 minClosurewords to know, back to the five quizzes (slides 21–22)
  6. 0:37–0:458 minExit ticket

Overview

This is the first data structure of the course: the one-dimensional array (4.3.A). Day 1 creates arrays and reaches single elements: what an array is and what it may hold (4.3.A.1), square brackets with an index (4.3.A.5), the default values new fills in (4.3.A.3), and initializer lists (4.3.A.4). Day 2 is size: the length attribute and why it never changes (4.3.A.2), and the valid index range with ArrayIndexOutOfBoundsException (4.3.A.6). Day 3 stores object references in an array, including slots that still hold null, and closes the topic.

Stay inside the boundary. Visiting every element with a loop is Topic 4.4, so every example reaches elements one index at a time; if a student asks “can a loop do this?”, say yes, next topic. No ArrayList, no 2D arrays, no enhanced for. Students already know the pieces this topic leans on: String indexes and StringIndexOutOfBoundsException (1.15), null and NullPointerException (1.13, 1.14), and default values for instance variables (3.4).

Keep one idea running through all three days: an index is how many steps from the start. The first element is 0 steps away, so the last of n elements is n - 1 steps away. The worksheet’s Fair Question after question 6 uses the same explanation.

Teacher note

The slides are the Mind the Index deck (22 slides, with speaker notes); slide numbers below refer to it. Slides 4, 7, 11, 14, and 17 are part dividers. Day 1 uses slides 2–13, Day 2 slides 14–18, Day 3 slides 19–22. The Mind the Index puzzle worksheet (9 questions, about 30 minutes) is split by day: questions 2 and 4 are homework after Day 1; question 3 is Day 2’s guided practice and questions 1, 5, and 6 are homework after Day 2; questions 7–9 are done in class on Day 3.

Demonstrations are in the topic’s examples/ folder (.snippet.java files hold only the statements for main): QuizScores, DayIndex, FirstScoreWrong, WrongElementType, DefaultValues, NullName, InitializerLater (Day 1); LengthDemo, GrowWrong, LengthMistakes, OffByOne, NegativeIndex, StoreOutOfBounds (Day 2); TeamRoster, SharedPlayer, EmptyRoster (Day 3). Before Day 2, check that students can create and run a file in the IDE.

Day 1 · Warm-up: Five quizzes, five variables

Show slide 2. Partners answer the prompt: the user types 3, so how do you print quiz 3’s score? Then the questions on the slide: how much code for 5 quizzes, for 30, and can the number 3 become the name quiz3?

Collect two ideas. With separate variables, a program needs one if per quiz to turn a number into a variable, so 30 quizzes means 30 declarations and a 30-branch chain. And there is no way to build the name quiz3 from the number 3. Tell students today’s tool fixes both: one name for all the scores, and a number that picks one of them.

Day 1 · Direct instruction: One name, many values

  1. Goals (slide 3). Read the five goals; goals 1–3 are today’s, 4 and 5 are Day 2’s.
  2. What an array is (4.3.A.1, slide 5). An array stores multiple values of the same type; each value is an element. Walk through the three pieces of int[] scores = new int[5];: the type int[], the name, and new int[5] making one array object with room for five int values. Point at the memory picture: one object, five elements.
  3. Element types (4.3.A.1, slide 6). The elements may be primitive values (double, boolean) or object references (String). Ask, “Which array holds references?” (songs.) Read the rule at the bottom aloud: the type on both sides must match, and the size goes only after new.

Misconception: An int[] can hold a double[], the way an int can be cast from a double

Students remember casting a double to an int (Topic 1.5) and expect arrays to convert too. They don’t: double[] and int[] are different kinds of objects, and Java never converts one array type to another. Show WrongElementType and its message, double[] cannot be converted to int[]. Mention the related slip int[5] scores; (Java reports ']' expected): the brackets in a type are always empty.

Day 1 · Direct instruction: Square brackets and an index

  1. Read and change one element (4.3.A.5, slide 8). temps[0] reads the first element; temps[2] = 66; replaces one element and leaves the others alone. Point at the index row under the boxes: indexes run 0 to 3 for four elements. Run QuizScores to show reading, changing, and adding elements.
  2. Any int expression (4.3.A.5, slide 9). Show the code and cover the output. Ask for each line before revealing: temps[day] is 74, temps[day - 1] is 65, temps[0] + temps[1] is 139. Stress that Java works out the expression first and then uses the result as the index. This is the answer to the warm-up: a number the user types can pick the element. Run DayIndex if there is time.

Misconception: The first element is at index 1

People count from 1, so “the first score” feels like scores[1]. Run FirstScoreWrong: it compiles, runs, and prints the second score with no message at all, because this is a logic error. Use the steps idea: the first element is 0 steps from the start. The element at index k is element number k + 1 when you count like a person.

Day 1 pause and try

Slide 10. Students write the output on mini whiteboards, then hold them up. Answer: 5.0 then 2.0. cost[1] becomes 2.5 * 2, which is 5.0, and cost[2] += 0.75 changes 1.25 to 2.0. Students who write 5 or 2 forgot the element type is double; students who write 8.0 used the old cost[1] instead of cost[0].

Day 1 · Direct instruction: Defaults and initializer lists

  1. Defaults (4.3.A.3, slide 12). Cover the output and ask what each println shows. Reveal: 0, 0.0, false, null. Connect to Topic 3.4: these are the same defaults instance variables get. Run DefaultValues.
  2. Initializer lists (4.3.A.4, slide 13). Values in braces create the array and fill it in one step: the number of values sets the length, and the first value goes in index 0. Then the bottom half: the same braces on a later line do not compile. Run InitializerLater to show illegal start of expression.

Misconception: A new String array holds empty strings

“Nothing stored yet” sounds like "", but every element of new String[n] holds null, which means no object at all. Run NullName: names[0].length() prints 3, then names[1].length() throws a NullPointerException because names[1] was never assigned. Ask, “What is the length of ""?” (0, because it is a real String.) Then, “What is the length of null?” (There isn’t one; there is no object to ask.)

Misconception: An initializer list can be assigned to an existing array later

The declaration int[] scores = {88, 92, 75}; works, so scores = {90, 95, 80}; looks like the same idea. The braces mean “array values” only right after a declaration; anywhere else Java does not know what type of array to build. To change an existing array’s values, assign the elements one at a time.

Day 1 · Independent practice: Independent practice

Puzzle worksheet questions 2 and 4 are homework, about 8 minutes. Question 2 asks for element [0] and the length after each creation statement; question 4 traces a points array that starts with defaults. Both use only Day 1 ideas.

Day 1 · Closure: Closure

Cold-call: “Using one array instead of five variables, which index holds quiz 1? Quiz 5?” (0 and 4.) Keep the answer on the board; Day 2 asks for the last index of any array.

Day 2 · Warm-up: Warm-up

On mini whiteboards: what does each element of new double[3] hold, and what does each element of new boolean[2] hold? (0.0 and false.) Then write one statement that creates an int array holding 4, 8, and 15 (int[] nums = {4, 8, 15};). Spot-check homework question 2’s last row: the 0 in {0, 5, 2, 8} is there because the list says so, not because it is a default.

Day 2 · Direct instruction: Length is fixed

  1. The length attribute (4.3.A.2, slide 15). Cover the output first. colors.length is 3, colors[colors.length - 1] is gold, and colors[1].length() is 4. Walk through the table: an array’s length is an attribute with no parentheses; a String’s length() is a method. Write on the board: the last element is always at arr.length - 1. Run LengthDemo.
  2. Length can never change (4.3.A.2, slide 16). Ask what prints before revealing. stock = new int[4]; makes a different array of four zeros and points stock at it; the old {12, 7} array is unchanged and no variable refers to it. So the output is 4 then 0, not 12. Run GrowWrong for the same idea with a scores array.

Misconception: Writing length() for an array, or assigning to length

Students carry length() over from String. Run LengthMistakes: Java reports cannot find symbol ... method length() for the parentheses and cannot assign a value to final variable length for scores.length = 4;. Give a rule that sorts the two: strings ask a method with (), arrays read an attribute without. If a program needs a different size, it creates a new array.

Misconception: new int[4] makes the old array bigger

On slide 16 many students predict stock[0] prints 12, because they picture the array stretching to four slots. Point at the after picture: two arrays, and the variable now refers to the new one. new always makes a brand-new array with default values.

Day 2 · Direct instruction: One past the end

Slide 18 (after the divider on slide 17). Valid indexes are 0 through length - 1; any other index throws an ArrayIndexOutOfBoundsException while the program runs (4.3.A.6). Cover the output and ask what prints. Answer: 74, then the exception; finished never prints. Point out that the message names both the bad index and the length. Run OffByOne, then NegativeIndex to show that an index below 0 fails the same way.

Misconception: arr[length] is the last element

The length is 4, so index 4 “should” be the last one. Return to the steps idea: four elements sit 0, 1, 2, and 3 steps from the start. Students met the same rule with the characters of a String in Topic 1.15. Have the class say the last index aloud for lengths 3, 10, and 1 (2, 9, and 0).

Misconception: Storing past the end adds an element

Students expect scores[3] = 60; on a three-element array to add a fourth score. Run StoreOutOfBounds: storing out of bounds throws the same exception as reading out of bounds, because the length was fixed at creation. If a program needs room for four, create new int[4] from the start.

Day 2 · Guided practice: Be the compiler

Puzzle worksheet question 3 in pairs. For each of the six snippets, partners first write on paper whether it compiles and what happens, then type it into the IDE (inside main) to check. Debrief by asking which errors the compiler caught and which it could not:

  • Rows 1–3 do not compile: mismatched element types, a list in braces after the declaration, and length() on an array.
  • Row 4 compiles and then crashes: the compiler does not track which indexes exist, so a[2] fails only while running.
  • Row 5 prints 3: s[1] is the String "hey", and length() is a String method.
  • Row 6 prints 0: new int[3] is a brand-new array of zeros.

Teacher note

If IDE access is not ready, run question 3 on paper and demonstrate rows 4 and 6 on the projector. Pairs who finish early can start homework question 6.

Day 2 · Independent practice: Independent practice

Puzzle worksheet questions 1, 5, and 6 are homework, about 12 minutes: expression values on a laps array, including laps[laps[3] - 5]; the snippet pool that needs index 0, stops.length - 1, and 2; and the crash-course program that stops at seats[3]. Question 6 asks students to write what prints before the crash and name the exception, and its key fixes the line with seats[seats.length - 1].

Day 2 · Closure: Closure

Cold-call: “An array has length 12. What are its first and last valid indexes? What happens with index 12?” (0 and 11; an ArrayIndexOutOfBoundsException while the program runs, not a compiler error.)

Day 3 · Warm-up: Warm-up

Write String[] floors = {"Lobby", "Gym", "Pool"}; and System.out.println(floors[-1]); on the board. Ask, “Some languages print the last element here. What does Java do?” (It compiles and throws an ArrayIndexOutOfBoundsException, index -1.) This is the worksheet’s Watch Out after question 6. Then check homework question 6: 14, 36, then the exception; done never prints.

Day 3 · Direct instruction: Arrays of object references

Slide 19 (4.3.A.1). new Pet[3] makes three slots, all null; no Pet exists yet. shelter[0] = new Pet("Biscuit"); creates one object and stores a reference to it. Cover the output and ask what prints. (Biscuit, then null.) Then ask what shelter[1].getName() would do: index 1 is valid, but there is no object in the slot, so it throws a NullPointerException.

Run TeamRoster to show creating objects into some slots and calling methods through the elements. Then run SharedPlayer: lineup[0] = star; copies a reference, so points added through lineup[0] show up through star. Changing lineup[0] to refer to another player does not change star.

Misconception: new Player[2] creates two players

Students read new and the class name and assume the objects are made. Run EmptyRoster: team[0] was filled, but team[1] was not, so calling addPoints on it throws a NullPointerException. Contrast the two crashes from this topic: an index outside the range is an ArrayIndexOutOfBoundsException; a valid index whose slot holds null is a NullPointerException. The fix is to create the object first, for example team[1] = new Player("Ben");.

Day 3 pause and try

Slide 20. Students write the output and label which length is which. Answer: 4 (words[1] is "kiwi", and length() is a String method), 3 (words.length, the number of elements), and f (the last element is "fig", and substring(0, 1) is its first letter). Anyone who writes 5 for the first line read words[1] as index 1 counting from 1, which is "apple".

Day 3 · Independent practice: Independent practice

Puzzle worksheet questions 7, 8, and 9 in class, alone or in pairs, about 12 minutes. Question 7 (two truths and a lie) uses an array of Locker objects with a shared reference and a null slot: claim 3 is the lie, because new Locker[3] makes no Locker objects. Question 8 is the Array and String face-off on length, bounds, and changing elements. Question 9 (who am I?) reviews the vocabulary. Circulate on question 7 and ask students who circle claim 2 whether index 2 is valid (it is; the slot is just empty).

Day 3 · Closure: Closure and exit ticket

Slide 21 reviews the vocabulary; ask students to match each word to an answer from question 9. Then slide 22: partners rewrite the five quiz variables from slide 2 as one array and complete the sentence starter. (Quiz 3 is at index 2 because the first quiz is at index 0. The last quiz is at index 4, or quizzes.length - 1.)

Give the exit ticket (about eight minutes). Question 1 checks creation, defaults, initializer lists, length, and access by index (4.3.A.2–4.3.A.5); question 2 the valid index range (4.3.A.6); question 3 creating an array with new, its defaults, and fixed length (4.3.A.1–4.3.A.3). Re-teach the weakest at the start of Topic 4.4, which needs arr.length - 1 as a loop bound.

Exit ticket

Question 1 · Multiple choice

What does this code print?

int[] tickets = new int[4];
String[] names = {"Ana", "Bo", "Cy"};
tickets[2] = names.length;
tickets[tickets.length - 1] = tickets[2] * 5;
System.out.println(tickets[0]);
System.out.println(tickets[3]);
System.out.println(names[names.length - 1]);
  1. null, then 15, then Cy, each on its own line
  2. 0, then 15, then Cy, each on its own line
  3. 0, then 15, then Bo, each on its own line
  4. Nothing: line 3 does not compile, because an int array cannot store a value taken from a String array
Check your reasoning

B. new int[4] fills all four elements with the default 0. The initializer list makes names with length 3, so line 3 stores 3 in tickets[2]. On line 4, tickets.length - 1 is 3, so tickets[3] gets 3 * 5, which is 15. tickets[0] was never assigned and still holds 0. The last element of names is at index 3 - 1 = 2, which is "Cy".

0
15
Cy

A uses null as the default, but null is the default only for reference types; an int element starts at 0. C counts from 1, but index 2 is the third element, "Cy". D misreads names.length: it is the int 3, the number of elements, not a String, so storing it in an int array compiles.

Question 2 · Multiple choice

What happens when this code runs?

double[] temps = {71.5, 68.0, 74.25};
int i = temps.length;
System.out.println(temps[i - 1]);
System.out.println(temps[i]);
System.out.println("done");
  1. It does not compile, because temps[i] uses an index that does not exist.
  2. It prints 74.25, then 0.0, then done.
  3. It prints 74.25, then throws an ArrayIndexOutOfBoundsException.
  4. It throws an ArrayIndexOutOfBoundsException before printing anything.
Check your reasoning

C. temps has length 3, so i is 3 and the valid indexes are 0, 1, and 2. Line 3 prints temps[2], which is 74.25. Line 4 asks for index 3, which throws an ArrayIndexOutOfBoundsException while the program runs, so done never prints. A is wrong because the compiler does not check which indexes exist; the error happens only while running. B pictures an extra element with a default value, but the length is fixed at 3 and nothing exists past the end. D treats temps[i - 1] as out of bounds too, but i - 1 is 2, the last valid index.

Question 3 · Multiple choice

A theater has 30 seats and stores the name of the person in each seat. On opening night, it adds a 31st chair. Which statement is correct?

  1. String[] seats = new String[29]; creates the array, because the indexes go from 0 to 29.
  2. String[] seats = new String[30]; creates the array, and right after it runs, seats[0] holds "".
  3. String[] seats = new String[30]; creates the array, and seats[30] = "Kai"; adds the 31st name by making the array one longer.
  4. String[] seats = new String[30]; creates the array, seats[0] starts as null, and holding 31 names needs a new array, because a length cannot change.
Check your reasoning

D. The size after new is the number of elements, 30. new fills every element with the default for its type, and the default for a reference type such as String is null. An array’s length is set when it is created and cannot be changed; seats = new String[31]; would make a different array whose elements all start as null.

A mixes up the size with the last index: new String[29] holds only 29 names, at indexes 0 through 28. B uses the empty string as the default, but "" is a real String object; a new String element holds null. C expects the array to grow, but index 30 does not exist in a 30-element array, so the assignment throws an ArrayIndexOutOfBoundsException.