Overview
Day 1 is the indexed for loop that visits every element (4.4.A.1, 4.4.A.2): the counter is the index, it starts at 0, and the test is i < arr.length because the last valid index is length - 1. Day 2 changes the start, test, and update to go backward, skip, or visit part of an array, writes the same traversals as while loops (including one that stops early with the bounds test first), and introduces the enhanced for loop (4.4.A.3). Day 3 is what the enhanced for loop variable really holds: assigning to it never changes the array (4.4.A.4), calling a mutator on it changes the object an element refers to but never the reference stored in the array (4.4.A.5), and any enhanced for loop can be rewritten as an indexed for or while loop (4.4.A.6).
Students created arrays, used arr[i], and met ArrayIndexOutOfBoundsException in Topic 4.3; they wrote while and for loops in Topics 2.7 and 2.8, short-circuit && in Topic 2.5, and classes with mutators and object references in Topics 3.3–3.6. Stay inside the topic boundary: the standard array algorithms (sum, average, minimum and maximum, counting, shifting, reversing in place) are Topic 4.5, and ArrayList and 2D arrays come later. Loop bodies today print, change elements one at a time, or call a mutator. If a student asks how to add up an array, say that is tomorrow’s topic.
Teacher note
The slides are the Lily Pad Loops deck (22 slides); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 uses slides 8–12, and Day 3 uses slides 13–22. The Lily Pad Loops puzzle worksheet (10 questions, about 30 minutes) is spread across the three days: questions 1 and 2 on Day 1, questions 4 and 8 in class on Day 2 with question 3 started as homework, questions 6 and 7 in class on Day 3, and questions 5, 9, and 10 as Day 3 homework.
Files whose names end in .snippet.java hold only the statements that go inside main; paste them into the main of a scratch class to run them. All files are in the topic’s examples/ folder.
- Day 1 demonstrations:
PrintTemps,DoublePoints,LengthParens.java(compile error),PastTheEnd(runtime error),TraceWords. - Day 2 demonstrations:
Backward,BackwardWrong(runtime error),EveryOther,MiddleOnly,WhileTemps,UntilDone,GuardOrderWrong(runtime error),EnhancedTemps,EnhancedNames,ValueAsIndex(runtime error),WrongVarType.java(compile error). - Day 3 demonstrations:
EnhancedAssign,ShoutNames,ShoutNamesFixed,TeamBonus.java,TeamReplace.java,TeamReplaceFixed.java,ThreeWays,RewriteWrong,RosterDay.java(optional extension). - Printed only (exit ticket):
ExitHops,ExitNames, andExitNamesWhile.
The deck’s code uses temps = {61, 64, 58, 70} (and a fifth value, 66, on slides 2 and 7); the guide’s files use {68, 71, 75, 70}. The behavior is the same; just warn students the numbers differ.
Day 1 · Warm-up: Five temperatures, or five hundred?
Show slide 2. Students write code to print every value of {61, 64, 58, 70, 66}, most likely five println statements, then answer the slide’s question with a partner: with 500 temperatures, what changes from one line to the next, and what stays the same? Collect the answer you want on the board: only the number in the brackets changes, and it goes 0, 1, 2, 3, … That is a counter, and Topic 2.8 gave them a loop built for counters.
Day 1 · Direct instruction: The loop counter is the index
- Goals (slide 3). Read the five goals; goal 1 is today, goals 2–4 are Day 2 and the start of Day 3, and goal 5 is Day 3.
- Traversal (4.4.A.1, slides 4–5). Define traversing an array: using a loop to reach all of its elements, or an ordered part of them, one after another. When the loop’s counter is used as the index, it is an indexed loop (4.4.A.2).
- The header (slide 5). Point to each part: start at 0 (the first index), test
i < temps.length(the last index islength - 1), updatei++(one element at a time). Ask: “Whytemps.lengthand not4?” The same loop then works for an array of any length. - Two jobs for
i. RunPrintTempsand trace it on the board with columnsi,i < 4?,temps[i], printed.ipicks the element and is also printed as the day number. Point out the last row: wheniis 4 the test is false, sotemps[4]is never touched. - Changing elements. Run
DoublePoints:points[i] = points[i] * 2reads the element, then stores back into the same slot. Tell students to remember this loop; on Day 3 a shorter loop will look like it does the same job and will not. - No parentheses. Show
LengthParens.javaand ask students to predict before you compile. It does not compile: an array’s length isscores.length, while aString’s islength(). Then runTraceWords, which uses both in one line (words.lengthin the header,words[k].length()in the body).
Misconception: length() on an array
Students carry length() over from String. Arrays use length with no parentheses; it is not a method. The compiler catches this (cannot find symbol ... method length()), so it is quick to fix, but it costs time on paper. TraceWords is the contrast to keep on the board.
Day 1 · Direct instruction: One step past the end
Slide 6. Ask students to predict the output of the <= loop before revealing it. The first four passes print all four values; then i is 4, 4 <= 4 is true, and temps[4] throws an ArrayIndexOutOfBoundsException. Run PastTheEnd to show the same crash in the IDE. Stress that the code compiles; the error happens only when it runs, because the compiler does not track what value i will hold. i <= temps.length - 1 is correct and means the same as i < temps.length.
Misconception: The loop should go up to the length
Students read “4 elements” and write i <= temps.length. The length counts elements, but indexes start at 0, so the last index is length - 1. Give them a check for any header: “What is the last value of i that passes the test? Is it a valid index?”
Day 1 · Guided practice: Which elements does each loop visit?
- Slide 7. Pairs write what each loop prints for
{61, 64, 58, 70, 66}on mini whiteboards, with a trace ofi. Loop A starts at 4 and steps by 2: it prints66,58,61(theniis -2 and the test fails). Loop B starts at 1 and stops beforelength - 1: it prints64,58,70. Say that changing the start, test, and update is still a traversal, an ordered part of the array; Day 2 looks at these loops properly. - Worksheet question 2 (pencil check). Pairs list the indexes each loop visits on an array of length 6. Answers:
0 1 2 3 4 5;1 3 5;5 4 3;0 3; and0to5, then a crash at 6. For each row, ask: “Which value ofifails the test first?”
Teacher note
Slide 7 previews Day 2 on purpose. If students are slow with loop A, trace only loop B today and come back to loop A in the Day 2 warm-up.
Day 1 · Independent practice: Independent practice
Students do worksheet question 1 (you’re the JVM) alone. The answer is A, 8 1: pads.length - 1 is 5, so i is 1 and 3, and the loop stops at 5. Check for the three distractors: B (test read as i < pads.length), C (started at 0), and D (update read as i++).
Day 1 · Closure: Closure
Each student says, or writes on a sticky note, the standard header for visiting every element of an array named scores, and finishes the sentence “The test is < and not <= because …” Look for “the last index is length - 1.”
Day 2 · Warm-up: Write three headers
On mini whiteboards, students write a for header for an array named stops that (a) visits every element, (b) visits every other element starting at 0, and (c) skips the first and last elements. Answers: for (int i = 0; i < stops.length; i++), the same with i += 2, and for (int i = 1; i < stops.length - 1; i++). Check each against the rule from Day 1: every index the body uses must be from 0 to length - 1.
Day 2 · Direct instruction: Backward and while traversals
- Backward (slides 8–9). Show the backward loop on slide 9 and run
Backward. Ask: “Why does it start atlength - 1and notlength? Why>= 0and not> 0?” Then runBackwardWrong: it starts atstops.length, so the very first pass readsstops[4]and the program crashes before printing anything. - Other steps and parts. Run
EveryOther(iis 0, 2, 4, then 6 fails the test) andMiddleOnly(start at 1, stop beforelength - 1). The test still protects the array: with an even-length array,i += 2stops before a bad index. - The while version (4.4.A.2, slide 9). A
whiletraversal is still indexed: declare the index before the loop, test it in the condition, use it in brackets, update it at the end of the body. RunWhileTempsand match each of its lines to the parts of theforheader.
Misconception: A backward loop starts at the length
Students think “start at the end” means arr.length. The length counts elements; the last index is one less. BackwardWrong crashes on its first pass, which makes the point quickly. The other half of the error is i > 0, which quietly skips index 0; worksheet question 8 is exactly that bug.
Misconception: Forgetting the update in a while loop
In a for loop the update sits in the header; in a while loop it is a separate statement that is easy to leave out. Without i++, i stays 0 and the loop prints the first element forever. Have students point to all three parts (start, test, update) in every while traversal they write.
Day 2 · Direct instruction: A while loop that stops early
Slide 10. The condition i < line.length && !line[i].equals("done") stops at the marker or at the end, whichever comes first, so it prints Ana and Ben. Run UntilDone, then ask: “What if there is no "done"?” Run GuardOrderWrong, which puts the marker test first: on a two-element array it prints wash and dry, then crashes reading tasks[2]. With the bounds test first, && short-circuits (Topic 2.5) and tasks[2] is never evaluated. Point out that i was declared before the loop, so it still exists afterward and can report where the loop stopped.
Misconception: The order of the two tests does not matter
Students know && means “both must be true” and assume order is irrelevant. With &&, Java skips the right side when the left side is false, so the bounds test protects the array only if it comes first. The decoy tile in worksheet question 4 is this exact error.
Day 2 · Guided practice: Worksheet questions 4 and 8
- Question 4 (code tiles). Pairs build
showUntilZero:int i = 0;, thenwhile (i < d.length && d[i] != 0) {,System.out.println(d[i]);,i++;,}. The decoy is the condition withd[i] != 0first, which crashes on arrayb(no 0) when it readsd[2]. - Question 8 (one-token fix). The backward loop prints only
9and3. Change>to>=on line 2, so index 0 is visited and7prints.
Day 2 · Direct instruction: The enhanced for loop
- The header (4.4.A.3, slides 11–12). Read
for (int t : temps)aloud as “for eachinttintemps.” The variable in the header is the enhanced for loop variable; on each pass it is assigned a copy of the next element, without using an index. Walk through slide 12’s pass table, then runEnhancedTemps: noi, no.length, no brackets. - What it cannot do. It always starts at the first element, always moves forward one element at a time, and never tells you the index. Because it never uses an index you could get wrong, it cannot run past the end.
- Any element type. Run
EnhancedNames: the loop variable is aString, soguest.length()works on it. Then showWrongVarType.javaand ask whether it compiles: no, the variable’s type must match the element type. - The variable is the element. Run
ValueAsIndex:temps[t]uses a temperature as an index and crashes at index 68.
Misconception: The loop variable is an index
Students used to indexed loops write temps[t]. In an enhanced for loop, t already holds the element. It crashes when the values are large (ValueAsIndex) and, worse, prints the wrong values silently when the values happen to be valid indexes. Ask: “On the first pass, what number is in t?”
Day 2 · Independent practice: Independent practice
Students start worksheet question 3 (you’re the compiler) and finish it as homework. Snippet 1 does not compile (a double element cannot be stored in an int variable); snippet 2 prints 2 then 3; snippet 3 does not compile (h.length()); snippet 4 prints 4 and 7, then crashes at h[2]; snippet 5 crashes at once, because x is 4 and h[4] is out of bounds. Snippets 4 and 5 compile because the compiler cannot know what index a variable will hold.
Day 2 · Closure: Closure
Write for (int x : nums) and for (int x = 0; x < nums.length; x++) on the board. Students hold up one finger if x is an element and two if it is an index, for each. Then: “Which one can print the position?”
Day 3 · Warm-up: The Think First prediction
Point students to the Think First box above worksheet question 2: int[] lily = {2, 4, 6}; and then for (int x : lily) { x = x * 10; }. Does lily now hold 20, 40, and 60? Take a show of hands and write the vote on the board without saying who is right. Today settles it.
Day 3 · Direct instruction: Changing the copy
- Slide 13 (4.4.A.4). Show both loops and ask for each one’s output before revealing it: the enhanced loop prints
61, the indexed loop prints71. Assigning totchanges onlyt, a copy. Use the guide’s picture: copying a phone number onto a sticky note and scribbling on the note does not change the contact list. Connect it to Topic 3.5: a parameter gets a copy of its argument in the same way. - Run
EnhancedAssign. Inside the looppreally is doubled (p is now 6, …), but the second loop shows the array still holds 3, 5, 8. Compare it withDoublePointsfrom Day 1, the indexed loop that did store the doubles. Settle the warm-up vote:lilystill holds 2, 4, 6. - Slide 14 (pause and try). Students write the output alone, then compare with a partner. Answer:
cat!,owl!,emu!, thencat. Inside the loop,wrefers to the new string; the array element still refers to"cat". RunShoutNamesandShoutNamesFixedto show the same bug withtoUpperCase()and its indexed fix.
Misconception: An enhanced for loop can change the array's values
The bug is silent: no compile error and no crash, the array just stays the same. Students often check the variable inside the loop (which did change) instead of the array afterward. Have them always print the array with a separate loop after the change, and give them the rule: to store a new value, you need arr[i] =, and only an indexed loop has an i.
Day 3 · Guided practice: Worksheet question 6
Pairs match the four loops to what f holds afterward. Answers: 1 → S (1 2 3, only the copy changed), 2 → Q (10 20 30), 3 → P (1 20 30, the test i > 0 skips index 0), 4 → R (7 2 3). Loop 4 is the one to discuss: it assigns to f[0], an element, so the array does change, and x reads each element as its pass begins (1, then 2, then 3, so f[0] becomes 2, 4, then 7).
Day 3 · Direct instruction: Arrays of objects
- Slides 15–16 (4.4.A.5). Ask first: “If the elements are objects, what does the loop variable get a copy of?” A reference (Topic 3.6). So
pis an alias of the object the element refers to. Trace slide 16 with two boxes for thePlantobjects and arrows from the array:p.water()follows the arrow and changes the object (5 becomes 7, 8 becomes 10);p = new Plant(1)moves onlyp’s arrow. Output:7and10. - Run
TeamBonus.java(a mutator through the loop variable: Ada 15, Bo 12) andTeamReplace.java(a new object assigned top: Ada 10, Bo 7, unchanged). Extend the sticky-note picture: now the note holds a house address; painting the door at that address changes the house, but writing a new address on the note changes only the note.
Misconception: Objects in an enhanced for loop work the same as int values
After Day 3’s first half, some students overcorrect and say an enhanced for loop can never change anything. Calling a mutator on the loop variable does change the object, because the variable and the element refer to the same object. What it cannot change is which object each element refers to. Keep the two statements on slide 16 side by side.
Day 3 · Guided practice: New plants
- Slide 17. Both versions start from a fresh
{new Plant(5), new Plant(8)}. Loop A prints5: it moves onlyp. Loop B prints1:garden[i] = new Plant(1)replaces the element. RunTeamReplaceFixed.javato show the indexed fix on thePlayerarray (Rookie 0twice). - Worksheet question 7 (two truths and a lie). Claim 2 is the lie:
pond[1]still refers to Bo. On each passf.hop()changes the real Ada or Bo (claim 1 is true), thenf = new Frog("Cy")moves onlyf, so the secondf.hop()goes to a Cy that is lost when the pass ends (claim 3 is true).
Day 3 · Direct instruction: Choosing and rewriting
- One traversal, three ways (4.4.A.6, slides 18–19). The rewrite trick: make the first line of the body
String p = pets[i];and the rest of the body stays the same. The slide’s caption sayspets[i]; in itswhileversion the index isk, so it ispets[k]there. RunThreeWaysto show all three printing the same lines. - Rewriting with the index by mistake. Run
RewriteWrong: it prints0,1,2instead of the ages, because it printsiinstead ofages[i]. - Which loop? (slide 20). Read the table. The direction to stress: every enhanced for loop can become an indexed loop, but not the reverse; tasks that need the position, a different order, part of the array, or a new value stored in a slot need an indexed
fororwhile. Slide 21 lists the vocabulary; leave it up during the closure.
Misconception: Printing the counter instead of the element
When rewriting an enhanced loop, students replace the loop variable with i instead of arr[i]. The code compiles and runs, so nothing warns them. Teach the rewrite as “declare the old variable as the first line of the body,” which makes the mistake hard to make.
Teacher note
If time allows, or as an extension for fast finishers, have students predict the output of RosterDay.java, which
uses an enhanced for loop with a mutator, an element assignment, an indexed loop, and a backward while loop on one
array of objects.
Day 3 closure and homework
Slide 22: partners finish the sentence starter, “The loop variable only holds a copy, so to change the array I need an index (arr[i] = in an indexed loop).” Homework is worksheet questions 5 (snippet pool: 0, < jumps.length, jumps[i]), 9 (face-off), and 10 (wrap-up reflection), plus anything left of question 3.
Day 3 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Score each question separately: question 1 checks indexed traversals with a changed start and step and the enhanced for copy (4.4.A.2–4.4.A.4), question 2 checks objects in an enhanced for loop (4.4.A.5), and question 3 checks choosing the while loop that matches an enhanced for loop (4.4.A.6). Re-teach the weakest one at the start of Topic 4.5.