Skip to content

Course navigation

For teachersTopic 3.8 · Lesson kit

Scope and Access

  • 3 class periods
  • 45 minutes each
  • Objective 3.8.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
3.8.A
Essential knowledge
3.8.A.13.8.A.2
Materials
Projector and the Where Names Live slide deckWhiteboard and markersMini whiteboards or scrap paper (scope maps and traces)IDE on every computerPrinted Where Names Live 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-uptwo methods, one name (slide 2)
  2. 0:05–0:1914 minDirect instructionscope, blocks, and reaching into another method (slides 3–6)
  3. 0:19–0:278 minDirect instructiona local variable starts over on every call (slide 7)
  4. 0:27–0:4013 minGuided practicefollow the cash (slide 8) and worksheet question 2
  5. 0:40–0:455 minClosurewhat lasts and what starts over

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  1. 0:00–0:055 minWarm-uptrace the clicker
  2. 0:05–0:1510 minDirect instructioninner blocks see out (slides 9–10)
  3. 0:15–0:227 minDirect instructionsame name in a row or nested (slide 11)
  4. 0:22–0:308 minGuided practicewhich names work here? (slide 12)
  5. 0:30–0:4010 minDirect instructiona parameter is a local variable (slides 13–15)
  6. 0:40–0:455 minIndependent practicestart worksheet question 4

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upfind the wandering parameter
  2. 0:05–0:1510 minDirect instructionscope versus private, and no modifiers on locals (slide 16)
  3. 0:15–0:249 minDirect instructionthe closer declaration wins (slides 17–18)
  4. 0:24–0:328 minGuided practicehow fast is the car? (slide 19) and worksheet question 3
  5. 0:32–0:386 minIndependent practiceworksheet questions 6 and 7
  6. 0:38–0:402 minClosurewhere does it live? (slides 20–21)
  7. 0:40–0:455 minExit ticket

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, BankPrivateError and BankPrivateMethodError (compile errors), PrivateLocal and PrivateParam (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

  1. Goals (slide 3). Read the five goals; they are spread over the three days.
  2. 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 the Recipe table on slide 5 row by row: servings is declared in the class body and every method can use it; s is the constructor’s; cups belongs to showFlour; eggs belongs to showEggs.
  3. Map a real class. Run TripReport (prints Average speed: 50 mph and Fuel used: 5.0 gallons). Students list each variable, where it is declared, and the lines where it can be used. speed is usable only inside printSpeed, gallons only inside printFuel, and drive only inside main.
  4. Reaching into another method (slide 6). Ask: “showEggs wants to use cups. Will it compile?” Then show the message: cannot find symbol, symbol: variable cups. “Symbol” is the compiler’s word for a name. Run TripSummaryError for the same error in the trip class.
  5. Compile time, not run time. In TripSummaryError, printSpeed is called before printSummary, and it still fails. Java checks scope by reading the code, before anything runs, so the order of the calls in main does 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

  1. Same code, two places (slide 7). Show the two Doorbell classes. On the left, rings is declared inside ring; 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 prints 1 three times and the right prints 1, 2, 3.
  2. 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 new rings. An instance variable belongs to the object and lasts as long as the object does.
  3. Run it. Run VisitCounterBug (prints 1, 1, 1) and VisitCounterFixed (prints 1, 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

  1. Slide 8. Pairs write the three lines of output for the Wallet. Answer: 15, 18, 10. spend(5) makes a local left of 15 and stores it in cash. refund(3) makes its own, different left, 15 + 3 = 18, and returns it, but never changes cash. The second spend(5) starts from 15 and returns 10. The common wrong last line is 13, which assumes refund changed cash.
  2. Worksheet question 2 (you’re the JVM), in pairs. Answer A (11 12 13): stamps is an instance variable and goes 1, 2, 3; bonus is local and is a new 10 on every call. Ask which wrong choice comes from which mistake: B and D let bonus remember its value between calls; C resets stamps as 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

  1. 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, and winner, and return winner; works because winner was declared in the method body. heavier(3, 8) prints 8 and heavier(9, 2) prints 9.
  2. Map four levels. Show CountLetter (prints 3). Students find each variable’s block: text is the instance variable, count belongs to the method body, i to the for loop, and current to the loop body. count++ sits three blocks deep and can still use count. Note that current is created fresh on every pass, just as each call makes fresh local variables.
  3. Trapped inside an if. Show FindLastError: position is declared inside the if body, so return position; after the loop is cannot find symbol. Ask for the fix before showing FindLastFixed (prints 5, then -1): declare position before 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

  1. 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, grow uses the constructor’s start and gets cannot find symbol: start existed only while the constructor ran.
  2. Run it. Run ThermostatDemo (prints Target: 74), then ThermostatResetError: reset uses the constructor’s parameter startTemp and does not compile.
  3. Save it (slide 15). If other methods need a parameter’s value, the constructor must store it in an instance variable. The fixed Plant stores start in step and prints 12. Run ThermostatResetFixed (prints Target: 72, then Target: 68).
  4. Parameter and local with the same name. Show ParamRedeclare: a local variable declared in raise with the parameter’s name is already 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

  1. 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.
  2. A second check (slide 16). Scope answers “where in this class can the name be used?” The access modifiers public and private answer “may another class use this member through an object?” Run BankDemo (prints 75.5): deposit calls the private helper isPositive, which is allowed because the call is inside Account. Then run BankPrivateError: checking.balance in main gives balance has private access in Account. Java found the name; this class just may not use it. BankPrivateMethodError shows the same message for a private method.
  3. Two messages, two causes. Read slide 16’s table: g.score in main is has private access; score alone in main is cannot find symbol, because an instance variable is not in scope in another class at all.
  4. 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 public or private would mean nothing, and Java rejects it. Run PrivateLocal (illegal start of expression) and PrivateParam (modifier private not allowed here). Fix both by deleting private.

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

  1. 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 stays null, and the program prints null. Renaming the parameter to t prints Sunrise.
  2. Run it. Run CoinJarBug (prints Coins: 0). Trace coins line by line: in the constructor, both sides of coins = coins; are the parameter; in getCoins, there is no parameter, so coins is the instance variable, still at its default value from Topic 3.4. Java gives no error because assigning a variable to itself is legal.
  3. A local can shadow too. Run ScoreboardBug (prints Lives: 0, then Lives: -1). int lives = 3; in the constructor has a type, so it declares a new local lives. The fix is to remove int. Compare score = 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?

  1. Slide 19. Students predict the output on whiteboards. Answer: 10. setSpeed’s parameter speed shadows the instance variable, so speed = speed; changes nothing; boost declares a local speed, so speed++ changes only the local. Ask what one change makes setSpeed work: rename the parameter, for example int s, and write speed = s;.
  2. Worksheet question 3 (one-word fix), in pairs. Answer: line 5, delete int. int warmest = temp; declares a local warmest inside the if block that shadows the instance variable and vanishes at the }, so getWarmest returns 0.

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.

Exit ticket

Question 1 · Multiple choice

What does this program print? Questions 2 and 3 use the same Tally class.

TallyExitTrace.java
public class TallyExitTrace
{
    public static void main(String[] args)
    {
        Tally t = new Tally(5);
        System.out.println(t.add(3));
        System.out.println(t.add(3));
        System.out.println(t.getCount());
    }
}

class Tally
{
    private int count;

    public Tally(int count)
    {
        count = count;
    }

    public int add(int amount)
    {
        int extra = 0;
        extra += amount;
        count += extra;
        return count;
    }

    public int getCount()
    {
        return count;
    }
}
  1. 8, 11, 11
  2. 3, 6, 6
  3. 3, 9, 9
  4. Nothing: line 18, count = count;, does not compile.
Check your reasoning

B. The constructor’s parameter is named count, so it shadows the instance variable: on line 18 both sides of count = count; mean the parameter. The instance variable count is never assigned and keeps its default value, 0.

Call (line) extra (local) instance count Printed
constructor, 5 (none) 0
add(3), 6 0, then 3 3 3
add(3), 7 0, then 3 6 6
getCount, 8 (none) 6 6

In add there is no local count, so count += extra; changes the instance variable. extra is a local variable, so each call makes a new one starting at 0.

  • A assumes the constructor stored 5 in the instance variable, but the parameter shadows it.
  • C lets extra remember its value between calls (3, then 6), but a local variable starts over each time the method runs.
  • D expects Java to reject the line, but assigning a variable to itself is legal; it compiles and does nothing useful.

Question 2 · Multiple choice

A main method in another class starts with Tally t = new Tally(5);. Which statement, written next in that main, compiles?

  1. System.out.println(t.count);
  2. System.out.println(extra);
  3. private int total = t.getCount();
  4. System.out.println(t.getCount());
Check your reasoning

D. getCount is public, so another class may call it through the object t. It prints 0.

  • A is wrong: count is private, so only code inside Tally may use it. Java reports count has private access in Tally.
  • B is wrong: extra is a local variable of add, so its scope is add’s body. In main it is not in scope, and Java reports cannot find symbol.
  • C is wrong: total would be a local variable of main, and local variables can never be declared public or private. Java reports illegal start of expression.

Question 3 · Multiple choice

A student adds this method to Tally so a tally can go back to the number it was created with: public void restart() { count = amount; }. It does not compile. Which statement explains why and gives a change that makes restart work?

  1. amount is private to add. Changing add’s header to public int add(public int amount) lets restart use it.
  2. amount has no value until add runs. Once add has been called, restart compiles and works.
  3. amount is a parameter of add, so its scope is only add’s body. Store the starting number in a new instance variable, such as private int start;, set it in the constructor, and write count = start; in restart.
  4. restart needs its own copy of the variable. Writing int amount = 0; as the first line of restart makes it work.
Check your reasoning

C. A parameter is a local variable of its method, so amount exists only inside add; in restart Java reports cannot find symbol. The starting number is the constructor’s parameter, which is also local and gone once the constructor ends. A value other methods need must be stored in an instance variable. (The constructor’s parameter also needs a name that does not shadow anything, such as int first, with start = first; and count = first;.)

  • A mixes up scope and access. private and public are never allowed on a local variable or parameter, and the header with public int amount does not compile.
  • B treats the parameter as if it lived on after the call. Scope is decided when the code compiles, and amount is out of scope in restart no matter what has run.
  • D compiles, but the new local amount is 0, so restart sets count to 0, not to the starting number.