Lesson 3.8: Scope and Access

Unit 3 · Lesson 3.8 · Code Mechanics

Lesson 3.8: Scope and Access

🕑 25–30 min· 8 Practice Questions· 4 Mastery Questions· Output Predictor + Bug Hunt

What You'll Learn

  • Define scope and identify what is accessible at any point in a class
  • Distinguish local, instance, and class variable scopes
  • Explain variable shadowing and use this to resolve it
  • Identify scope-related compile errors on for loop variables and redeclarations

Key Vocabulary

Term Definition
scope The region of code in which a variable is accessible
local variable Declared inside a method or block; only accessible within that method/block
instance variable Declared in class body outside any method; accessible throughout the class
class variable Declared with static in class body; accessible to all instances and static methods
block Code enclosed in { }; variables declared inside are local to that block
variable shadowing A local variable with the same name as an instance variable; the local variable takes precedence inside the block
lifetime How long a variable exists in memory: local = method call; instance = object's lifetime

CED EK 3.8 — Scope and Access

Scope determines where a variable can be used. A local variable's scope is the block in which it is declared. An instance variable's scope is the entire class. A class variable (static) is also accessible throughout the class. When a local variable has the same name as an instance variable, the local variable shadows the instance variable within that block.

Levels of Scope

Three Levels in One Class

public class Account {
    private double balance;          // instance scope: whole class
    private static int count = 0;   // class scope: whole class

    public void deposit(double amount) {
        double fee = 1.50;           // local scope: this method only
        balance += amount - fee;
    }

    public double getBalance() {
        // fee is NOT accessible here -- out of scope
        return balance;
    }
}

Variable Shadowing

Shadowing Bug

public class Player {
    private int score;

    public void addPoints(int score) {   // shadows instance var!
        score += 10;   // modifies parameter, NOT instance var
        // to fix: this.score += 10; or this.score = score + 10;
    }
}

When parameter score shadows instance variable score, plain score inside the method refers to the parameter. Use this.score to explicitly reference the instance variable.

Block Scope in for Loops

Loop Variable Is Local

public void printSums(int n) {
    int total = 0;
    for (int i = 1; i <= n; i++) {
        total += i;  // total is accessible: declared in same method
        // i is accessible here
    }
    // i is NOT accessible here -- declared in for loop header
    System.out.println(total);
}

AP Trap: Local Variable Declared in Loop Not Accessible After Loop

for (int k = 0; k < 5; k++) { /* k accessible here */ }
// k NOT accessible here -- compile error

Variables declared in the for loop header are scoped to the loop body.

AP Trap: Declaring Same Variable Twice in Same Scope

public void method() {
    int x = 5;
    int x = 10;  // COMPILE ERROR: x already declared
}

You cannot redeclare a variable in the same scope. In nested blocks, you can shadow outer variables.

AP Trap: this.varName Required When Name Is Shadowed

public Dog(String name) {
    name = name;     // BUG: parameter shadows instance var
    this.name = name; // CORRECT
}

This is the same constructor bug from 3.4 -- explained here from the scope perspective.

Real-World Connection: Think of scope like employee security badges. A local variable is a day pass (only works today). An instance variable is a permanent badge (works as long as the employee object exists).

Summary

  • Local variables are declared inside a method/block and are only accessible within that block.
  • Instance variables are accessible throughout the class in which they are declared.
  • When a local variable and instance variable share a name, the local variable shadows the instance variable.
  • Use this.varName to explicitly access the instance variable when shadowing occurs.
  • Variables declared in a for loop header are scoped to the loop body.
Tier 2 · AP Practice

Practice Questions

MCQ 1
Which variables are accessible at the comment line?
public class Engine {
    private int rpm;
    public void rev(int boost) {
        int extra = boost * 2;
        // <-- here
    }
}
A rpm only
B rpm, boost, and extra
C boost and extra only
D rpm and boost only
B is correct. rpm (instance), boost (parameter), extra (local) are all in scope.
MCQ 2
Will NOT compile. Why?
public void printLast(int n) {
    for (int i = 0; i < n; i++) { int sq = i*i; }
    System.out.println(i);
}
A Loop variable must be declared outside the loop
B i is out of scope after the loop
C sq cannot be used outside its block
D Parameter n conflicts with i
B is correct. i is scoped to the loop. println(i) after the loop is a compile error.
MCQ 3
In public void award(int score) { score += 50; }, score refers to...
A The instance variable score
B A new local variable
C Both simultaneously
D The parameter score -- the instance variable is shadowed
D is correct. Parameter shadows instance variable. Use this.score for instance var.
MCQ 4
Which correctly fixes a shadowing bug?
A public void setAge(int age) { age = this.age; }
B public void setAge(int age) { age = age; }
C public void setAge(int age) { this.age = age; }
D public void setAge(int age) { super.age = age; }
C is correct. this.age = instance var; age = parameter. Assign parameter to instance var.
MCQ 5
After this code, what is total?
int total = 0;
for (int j = 1; j <= 4; j++) { int step = j*2; total += step; }
A 4
B 20
C 8
D 10
B is correct. steps: 2+4+6+8=20.
MCQ 6
The following has a compile error. What is it?
public void compute(int val) {
    int result = val * 2;
    int result = val + 10;
}
A result is an instance variable and can't be redeclared
B result can't be used in println without casting
C result is declared twice in the same scope
D val can't be multiplied and added in the same method
C is correct. Declaring result twice in the same scope is a compile error.
MCQ 7
Which has the LONGEST lifetime?
A Variable declared inside a for loop
B Variable declared as a method parameter
C Private instance variable
D Variable declared inside an if block
C is correct. Instance variables live for the entire object lifetime.
MCQ 8
What is the scope bug in this code?
public void addCookies(int cookies) {
    cookies = cookies + 10;
}
where cookies is also a private instance variable.
A cookies can't be both a parameter and an instance variable
B cookies = cookies + 10 modifies the parameter; this.cookies unchanged
C Adding 10 to a parameter is a compile error
D cookies must be declared differently
B is correct. Parameter shadows instance var. this.cookies is untouched. Fix: this.cookies = cookies + 10;
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor: Scope
Predict output based on variable scope.
Question 1 of 2  ·  Score: 0

Done!
You got 0 of 2 correct.
Bug Hunt: Scope
Click the buggy line, or 'No bug'.
Question 1 of 3  ·  Score: 0
No bug — code is correct
Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: Scope and Access

MCQ 1
After acct.update(20.0) where update does balance = balance + 50.0; and balance is also a private instance variable starting at 100.0, what is the instance variable's value?
⚠ Predict the answer before reading the options.
A 150.0
B 120.0
C 100.0
D 70.0
C is correct. Parameter shadows instance variable. balance += 50 changes the local copy. Instance var stays 100.0.
MCQ 2
Variable x is declared inside an if block. Where is it accessible?
A Throughout the entire method
B Only within the if block
C Throughout the entire class
D Only on the declaration line
B is correct. Block-local variable: only accessible within that block.
MCQ 3
I. For loop variable in header accessible after loop
II. Instance variable accessible by any method in its class
III. this.x refers to instance variable even when parameter x shadows it
Which are TRUE?
A I and II only
B II only
C II and III only
D I, II, and III
C is correct. II and III are true. I is false: loop variable scoped to loop body.
MCQ 4
A constructor has parameter cash AND declares double cash = 50.0; locally. Result?
A this.cash set to 50.0
B Compile error: cash declared twice in same scope
C this.cash set to parameter value
D Both versions accessible
B is correct. Declaring cash twice (parameter + local variable) in the same scope is a compile error.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]