Overview
This topic has one learning objective, 3.8.A: explain where variables can be used in the code. Day 1 names the idea students met in Topic 2.8 (a loop variable “belongs to the loop”): a variable’s scope is the part of the program where its name can be used, and a local variable can be used only from its declaration to the end of its block (3.8.A.1). Day 1 also covers time: a local variable is made fresh on every call and cannot remember anything between calls. Day 2 covers blocks inside methods (inner blocks see outer variables, not the reverse; a name cannot be declared again while it is still in scope) and parameters as local variables of their constructor or method (3.8.A.1). Day 3 separates scope from public and private, explains why local variables and parameters can never take an access modifier (3.8.A.1), and teaches shadowing: when a local variable or parameter has the same name as an instance variable, the name means the local one inside that body (3.8.A.2).
Students wrote classes with private instance variables, constructors, and methods in Topics 3.3–3.5, and met class variables in Topic 3.7. Stay inside the topic boundary: the keyword this is Topic 3.9. When students ask how to reach a shadowed instance variable, say that the next topic gives a way, and that today’s fix is a parameter name that does not clash. Do not use arrays or ArrayList.
Teacher note
The slides are the Where Names Live deck (21 slides, with speaker notes that hold the answers to the Pause and Try slides); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 uses slides 9–15, and Day 3 uses slides 16–21. The Where Names Live puzzle worksheet (9 questions, about 30 minutes) is split across the three days: question 2 in class on Day 1; question 4 started in class on Day 2, with questions 4 and 5 as Day 2 homework; questions 3, 6, and 7 in class on Day 3; and questions 1, 8, and 9 as Day 3 homework. Question 1’s last blank is the word shadow, so hold it until Day 3.
Every demonstration file below is in the topic’s examples/ folder and holds two classes in one file: a class with main and the class being studied, written without public. Tell students this is only so each example fits in one file; in the course and on the exam each class is public and has its own file. Files ending in .snippet.java hold only the statements that go inside main.
- Day 1 demonstrations:
TwoTotals,TripReport,TripSummaryError(compile error),VisitCounterBug,VisitCounterFixed. - Day 2 demonstrations:
ClickerTrace,CountLetter,FindLastError(compile error),FindLastFixed,TwoLoopsSameName.snippet.java,BeforeLoopSameName.snippet.java(compile error),ThermostatDemo,ThermostatResetError(compile error),ThermostatResetFixed,ParamRedeclare(compile error). - Day 3 demonstrations:
PlayerNameError(compile error),BankDemo,BankPrivateErrorandBankPrivateMethodError(compile errors),PrivateLocalandPrivateParam(compile errors),CoinJarBug,ScoreboardBug. - Printed only (exit ticket):
TallyExitTrace.
Most of today’s mistakes are compile errors, so the demonstrations are mostly “predict, then compile.” Have students commit to a prediction on a whiteboard before every run.
Day 1 · Warm-up: Two methods, one name
Show slide 2. Two methods in the same class each declare a local variable named total. Ask: “Do they clash? Can one method see the other’s total?” Students write yes or no for each question on a whiteboard. Take a quick count, then run TwoTotals: it compiles and prints 10.0, 15.0, 10.0. Adding 5 to total in costWithShipping did not change the total in itemCost. Do not explain why yet; today’s lesson is the reason.
Day 1 · Direct instruction: Scope and local variables
- Goals (slide 3). Read the five goals; they are spread over the three days.
- Scope and blocks (3.8.A.1, slides 4–5). A block is code between a matching
{and}: a method body, a constructor body, a loop body, an if body. A local variable is declared in a block (or in the header that opens one, such as a for loop header). Its scope runs from its declaration to the closing brace of that block. Walk theRecipetable on slide 5 row by row:servingsis declared in the class body and every method can use it;sis the constructor’s;cupsbelongs toshowFlour;eggsbelongs toshowEggs. - Map a real class. Run
TripReport(printsAverage speed: 50 mphandFuel used: 5.0 gallons). Students list each variable, where it is declared, and the lines where it can be used.speedis usable only insideprintSpeed,gallonsonly insideprintFuel, anddriveonly insidemain. - Reaching into another method (slide 6). Ask: “
showEggswants to usecups. Will it compile?” Then show the message:cannot find symbol,symbol: variable cups. “Symbol” is the compiler’s word for a name. RunTripSummaryErrorfor the same error in the trip class. - Compile time, not run time. In
TripSummaryError,printSpeedis called beforeprintSummary, and it still fails. Java checks scope by reading the code, before anything runs, so the order of the calls inmaindoes not matter.
Misconception: If one method runs first, the next method can use its variables
Students picture variables piling up as the program runs, so a value computed earlier should be “there” later. Scope is decided by where the declaration is written, not by which method ran first, and it is checked before the program runs. Point to TripSummaryError: printSpeed runs first and printSummary still cannot see speed. To share a value between methods, store it in an instance variable.
Day 1 · Direct instruction: A local variable starts over
- Same code, two places (slide 7). Show the two
Doorbellclasses. On the left,ringsis declared insidering; on the right, it is an instance variable. Ask students to predict all three lines of output for each before you point to the output columns: the left prints1three times and the right prints1,2,3. - Why. A local variable is created when its declaration runs and is gone when its block ends. Every call runs
int rings = 0;again and makes a newrings. An instance variable belongs to the object and lasts as long as the object does. - Run it. Run
VisitCounterBug(prints1,1,1) andVisitCounterFixed(prints1,2,3). State the rule from the slide: if a value must still be there on the next call, it belongs in an instance variable.
Misconception: A local variable remembers its value between calls
Students carry over the counting pattern from Unit 2, “start at 0, add 1,” and put it inside a method that is called many times. Every call makes a fresh local variable, so the count never grows. Ask: “Which line runs again on every call?” and have them point to the declaration. VisitCounterBug and slide 7 show the symptom: the same small number every time.
Day 1 · Guided practice: Follow the cash
- Slide 8. Pairs write the three lines of output for the
Wallet. Answer:15,18,10.spend(5)makes a localleftof 15 and stores it incash.refund(3)makes its own, differentleft, 15 + 3 = 18, and returns it, but never changescash. The secondspend(5)starts from 15 and returns 10. The common wrong last line is13, which assumesrefundchangedcash. - Worksheet question 2 (you’re the JVM), in pairs. Answer A (
11 12 13):stampsis an instance variable and goes 1, 2, 3;bonusis local and is a new 10 on every call. Ask which wrong choice comes from which mistake: B and D letbonusremember its value between calls; C resetsstampsas if it were local too.
Teacher note
The worksheet’s Think First box asks whether a local total that starts at 0 and adds 10 reaches 30 after three calls; question 2 settles it. Point that out when you hand out the worksheet. Students keep the worksheet for all three days.
Day 1 · Closure: Closure
Each student writes one sentence for each kind of variable: “An instance variable lasts as long as _____. A local variable lasts until _____.” Look for “the object” and “the end of its block (or the end of the call).”
Day 2 · Warm-up: Trace the clicker
Show ClickerTrace without running it. Students trace it on whiteboards, keeping track of the local presses and the instance variable total. Answer: 2, 3, 4. Students who wrote 2, 4, 6 treated presses as if it remembered its value; send them back to yesterday’s rule before moving on.
Day 2 · Direct instruction: Inner blocks see out
- Nested blocks (3.8.A.1, slides 9–10). A method with a loop or an if statement has blocks inside blocks. Code in an inner block can use the outer block’s variables; code in an outer block cannot use a variable declared in an inner block. On slide 10, the if body can use
a,b, andwinner, andreturn winner;works becausewinnerwas declared in the method body.heavier(3, 8)prints8andheavier(9, 2)prints9. - Map four levels. Show
CountLetter(prints3). Students find each variable’s block:textis the instance variable,countbelongs to the method body,ito the for loop, andcurrentto the loop body.count++sits three blocks deep and can still usecount. Note thatcurrentis created fresh on every pass, just as each call makes fresh local variables. - Trapped inside an if. Show
FindLastError:positionis declared inside the if body, soreturn position;after the loop iscannot find symbol. Ask for the fix before showingFindLastFixed(prints5, then-1): declarepositionbefore the loop, in the block where the result is needed, and assign to it inside the if. Declaring a variable before a block is how you carry a result out of it.
Misconception: A variable declared inside an if or loop is still there afterward
Students declare a result where they compute it, inside the if or loop, then use it after the closing brace. Have them draw a box around each block and check that every use of a name is inside the box where it was declared. The fix is to declare the variable in the outer block, before the inner block starts, and assign to it inside.
Day 2 · Direct instruction: Same name in a row or nested
Slide 11. Run TwoLoopsSameName.snippet.java (prints 1, 2, 3, 10, 20, 30): two loops one after the other may each declare their own i, because the first i is gone before the second loop starts. Then show BeforeLoopSameName.snippet.java: an i declared before a loop is still in scope inside it, so the loop header cannot declare another i, and Java reports variable i is already defined. The rule from the slide: while a variable is in scope, an inner block cannot declare another with the same name. The fix is a different name, or dropping the type so the statement assigns to the existing variable.
Misconception: Reusing a name that is still taken
Students reuse favorite names like i and total without checking whether the first one is still in scope. Ask: “Has the block where the first one was declared closed yet?” In a row, it has; nested, it has not. If the student meant the existing variable, the fix is to remove the type, not to rename.
Day 2 · Guided practice: Which names work here?
Slide 12. Pairs fill in which of n, sum, k, and sq can be used at spot A and at spot B. Answer: at spot A (inside the loop body) all four; at spot B (after the loop) only n and sum. Using k or sq at spot B is cannot find symbol. Ask where n was declared; students who say “nowhere” have not yet seen that a parameter is a variable of the method, which leads into the next section.
Day 2 · Direct instruction: A parameter is a local variable
- The rule (3.8.A.1, slides 13–14). A parameter is declared in the header that opens the constructor’s or method’s block, so it is a local variable of that body. It can be used anywhere in the body and nowhere else, and a new copy is made on every call. On slide 14,
growuses the constructor’sstartand getscannot find symbol:startexisted only while the constructor ran. - Run it. Run
ThermostatDemo(printsTarget: 74), thenThermostatResetError:resetuses the constructor’s parameterstartTempand does not compile. - Save it (slide 15). If other methods need a parameter’s value, the constructor must store it in an instance variable. The fixed
Plantstoresstartinstepand prints12. RunThermostatResetFixed(printsTarget: 72, thenTarget: 68). - Parameter and local with the same name. Show
ParamRedeclare: a local variable declared inraisewith the parameter’s name isalready defined. The parameter and the local variable share one block. By contrast, two different methods may each have a parameter with the same name, because their bodies are separate blocks.
Misconception: The class remembers what the constructor was given
Students treat a constructor parameter as if it belonged to the object, because the constructor and the methods sit in the same class. The class only remembers what was stored in an instance variable. Ask of every parameter a method seems to need: “Was it copied into an instance variable?” ThermostatResetError and slide 14 show the error; ThermostatResetFixed and slide 15 show the fix.
Day 2 · Independent practice: Independent practice
Students start worksheet question 4 (pencil check: map the scope of every variable in Password) in the last five minutes and finish it, with question 5 (code tiles), as homework. In question 4, only secret and found can be used on line 16; s is the constructor’s parameter and can be used on neither line. In question 5 the decoy is a second String letter = "A"; inside the if, which is already defined.
Day 3 · Warm-up: Find the wandering parameter
Show PlayerNameError without running it. Students find the line that will not compile and write the error message they expect. Answer: line 23 uses the constructor’s parameter playerName inside greet, so it is cannot find symbol; the fix is to use the instance variable name, which the constructor already filled. Go over question 4 and question 5 from the homework if many students missed them.
Day 3 · Direct instruction: Scope versus private
- Instance variables are in scope everywhere in their class. The class body is the outermost block, and every constructor and method sits inside it, so by the inner-sees-out rule every method can use every instance variable and call every other method.
- A second check (slide 16). Scope answers “where in this class can the name be used?” The access modifiers
publicandprivateanswer “may another class use this member through an object?” RunBankDemo(prints75.5):depositcalls theprivatehelperisPositive, which is allowed because the call is insideAccount. Then runBankPrivateError:checking.balanceinmaingivesbalance has private access in Account. Java found the name; this class just may not use it.BankPrivateMethodErrorshows the same message for a private method. - Two messages, two causes. Read slide 16’s table:
g.scoreinmainishas private access;scorealone inmainiscannot find symbol, because an instance variable is not in scope in another class at all. - No modifiers on locals (3.8.A.1). An access modifier decides which classes may use a member through an object. A local variable cannot be used outside its own block, not even by another method of the same class, so
publicorprivatewould mean nothing, and Java rejects it. RunPrivateLocal(illegal start of expression) andPrivateParam(modifier private not allowed here). Fix both by deletingprivate.
Misconception: Using an instance variable's name alone in another class
Students write balance in main and expect has private access. With no object and dot, balance is just an unknown name in main, so Java says cannot find symbol. Another class reaches a member only through an object, as in checking.getBalance(), and only if the member is public.
Misconception: Making a local variable private to protect it
Students who learned “make it private” in Topic 3.3 add private to local variables, or cut and paste an instance variable declaration into a method with private still on it. The code does not compile. Scope already protects a local variable more than private could. When a variable moves into a method, its access modifier comes off.
Misconception: Fixing every error the compiler lists
PrivateLocal produces more than one message, and students try to fix each line. A stray private confuses the compiler, and the later messages disappear once the first is fixed. Teach them to fix the first error and recompile.
Day 3 · Direct instruction: The closer declaration wins
- Shadowing (3.8.A.2, slides 17–18). A local variable cannot reuse the name of another local still in scope, but it may share a name with an instance variable. When it does, the name means the local variable or parameter everywhere it is in scope; it shadows the instance variable. On slide 18,
title = title;copies the parameter into itself, the instance variable staysnull, and the program printsnull. Renaming the parameter totprintsSunrise. - Run it. Run
CoinJarBug(printsCoins: 0). Tracecoinsline by line: in the constructor, both sides ofcoins = coins;are the parameter; ingetCoins, there is no parameter, socoinsis the instance variable, still at its default value from Topic 3.4. Java gives no error because assigning a variable to itself is legal. - A local can shadow too. Run
ScoreboardBug(printsLives: 0, thenLives: -1).int lives = 3;in the constructor has a type, so it declares a new locallives. The fix is to removeint. Comparescore = 0;on the next line, which has no type and works.
Misconception: Shadowing would be a compile error
Every other mistake today stopped the compiler. Shadowing compiles and runs, and the symptom is an instance variable stuck at its default, 0, 0.0, false, or null. Give students two questions to ask in the constructor or method that should set it: “Is there a parameter with the same name?” and “Does the assignment start with a type?” Today’s fix is to rename the parameter or remove the type; Topic 3.9 adds another way.
Day 3 · Guided practice: How fast is the car?
- Slide 19. Students predict the output on whiteboards. Answer:
10.setSpeed’s parameterspeedshadows the instance variable, sospeed = speed;changes nothing;boostdeclares a localspeed, sospeed++changes only the local. Ask what one change makessetSpeedwork: rename the parameter, for exampleint s, and writespeed = s;. - Worksheet question 3 (one-word fix), in pairs. Answer: line 5, delete
int.int warmest = temp;declares a localwarmestinside the if block that shadows the instance variable and vanishes at the}, sogetWarmestreturns0.
Day 3 · Independent practice: Independent practice
Students work worksheet question 6 (snippet pool) and question 7 (you’re the compiler) alone. In question 6, the holes are n, n, and battery; a parameter named name would shadow the instance variable and print null: 40. In question 7, rows 1 and 4 compile (12.0 and 7); row 2 is has private access, row 3 and row 5 are cannot find symbol, and row 6 is illegal start of expression. Questions 1, 8, and 9 are homework.
Teacher note
Question 7 is the best single check on today’s distinctions. If time is short, collect it instead of question 6. In question 8 the lie is claim 3: start is the constructor’s parameter, so getSeconds cannot use it and must return seconds.
Day 3 · Closure: Closure and exit ticket
Spend one minute on slide 20 (vocabulary) and one on slide 21 (where does it live?): pairs say which variable is local (the counter used while one round is scored) and which is an instance variable (the high score that survives every round), using the sentence starter. Then give the exit ticket (about five minutes). Score each question separately: question 1 checks local variables starting over and shadowing (3.8.A.1, 3.8.A.2), question 2 scope versus private and modifiers on locals (3.8.A.1), and question 3 parameters as local variables (3.8.A.1). Re-teach the weakest one at the start of Topic 3.9, which builds directly on shadowing.