Reference Guide

Key Topics


Term Definition Example
Scope The region of code where a variable name can be used. inside the { } it was declared in
Local variable Declared inside a method, constructor, or loop body. Dies at the closing brace. int total = 0;
Parameter Declared in a method or constructor header. Lives for the whole body. public void charge(double amount)
Instance variable Declared in the class, outside every method. Visible to the whole class. private double balance;
Shadowing A local or parameter with the same name as a field hides the field. balance = balance;
this The object the method was called on. this.x always means the field. this.balance = balance;
private Only the declaring class can read or write it. private String owner;
public Any class can use it. public double getBalance()
Accessor / Mutator Public methods that read (getter) or change (setter) a private field. getBalance(), charge(4.50)
  • Local variables and parameters cannot have public or private on them
  • Instance variables are usually private; other classes go through accessors and mutators

Where Each Variable Lives

Variable Type Declared In Accessible In public/private Allowed?
Instance variable Inside the class, outside methods Everywhere in the class Yes (usually private)
Parameter The method/constructor header Only inside that method/constructor No
Local variable Inside a method or loop body Only inside that specific block No

Reading Code on the Exam

  • Name used after a closing brace? → compile error
  • Parameter or local spelled like a field? → the field is shadowed, look for this.
  • name = name; in a constructor? → compiles, but the field stays null or 0
  • int score = 0; inside a method when score is a field? → a new local, the field never changes
  • Another class touching a private field directly? → compile error

College Board Requirements

AP CSA Unit 3, Topic 3.8 Scope and Access. Paraphrased from the course and exam description (College Board, 2025):

  • 3.8.A.1 Local variables can be declared in the body of constructors and methods. They may only be used within that constructor or method and cannot be declared public or private.
  • 3.8.A.2 When a local variable has the same name as an instance variable, the name refers to the local variable, not the instance variable.
  • 3.8.A.3 Formal parameters and variables declared in a method or constructor can only be used within that method or constructor.

The College Board tests this topic almost entirely through “what is printed” and “which line does not compile” questions, so the practice below is built around tracing rather than writing new classes.


Lesson Plan

Learning Objective: Determine where a variable can be used, recognize when a local variable shadows an instance variable, and access private fields correctly from other classes.

Success Criteria: You can name a variable’s scope from its declaration, fix a shadowing bug with this, and explain why a private field needs public accessors and mutators.

Tech Talk

Every variable lives inside a pair of braces. Step outside them and the name is gone.

Read code by asking two things: where was this name declared, and is there a closer declaration with the same spelling?

Code Runner Challenge

Predict all three printed lines first, then run it. Then uncomment the println(i) line and read the compiler message.

View IPYNB Source
public class IDCard {
    private double balance;                 // instance variable: the whole class sees it

    public IDCard(double balance) {         // parameter: this constructor only
        this.balance = balance;             // this.balance = the field, balance = the parameter
    }

    public void chargeMonth(int days) {
        double total = 0;                   // local: the rest of this method
        for (int i = 0; i < days; i++) {    // i: the loop only
            total += 2;
        }
        balance -= total;                   // no local named balance here, so this is the field
    }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Examples

A. Scope and shadowing. The IDCard class shows which braces each variable lives in

Three things get mixed up a lot:


for (int i = 0; i < 3; i++) { }   // i is gone after this brace
System.out.println(i);             // compile error

balance = balance;                 // parameter assigned to itself, the field is untouched
this.balance = balance;            // the field is assigned

Terminology:

A local variable is destroyed when its block ends. A parameter is a local that lives for the whole method. A parameter or local that shadows a field hides it, and only this. can reach the field again.


Code Runner Challenge

Run it, then uncomment card.balance = 1000000; and see what the compiler says

View IPYNB Source
// CODE_RUNNER: Predict all three printed lines first, then run it. Then uncomment the println(i) line and read the compiler message.
// Scope and Shadowing Examples
public class IDCard {
    // Instance variables: visible in every method of this class
    private String owner;
    private double balance;

    // Step 1: A constructor with parameters that shadow the fields
    public IDCard(String owner, double balance) {
        this.owner = owner;        // this.owner = the field, owner = the parameter
        this.balance = balance;
    }

    // Step 2: A method with a parameter, a local, and a loop variable
    public void chargeMonth(double perDay, int days) {
        double total = 0;                        // local: lives until the method returns
        for (int i = 0; i < days; i++) {         // i: lives only inside the loop
            double fee = perDay + (i * 0.25);    // fee: lives only inside this iteration
            total += fee;
        }
        // System.out.println(i);                // COMPILE ERROR: i is out of scope here
        balance -= total;                        // the field: no local named balance in this method
    }

    // Step 3: A shadowing bug -- the field never changes
    public void refundBroken(double amount) {
        double balance = this.balance + amount;  // declares a NEW local named balance
    }

    // Step 4: The same method, fixed
    public void refund(double amount) {
        balance = balance + amount;              // no local named balance, so this is the field
    }

    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    public static void main(String[] args) {
        IDCard card = new IDCard("Maya", 50.00);
        card.chargeMonth(2.00, 3);
        System.out.println(card.getOwner() + " after charges: " + card.getBalance());

        card.refundBroken(5.00);
        System.out.println("after refundBroken: " + card.getBalance());   // unchanged

        card.refund(5.00);
        System.out.println("after refund: " + card.getBalance());         // + 5.0
    }
}
IDCard.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

B. Access modifiers. The Kiosk class shows what private lets another class do

Common access mistake:


card.balance = 1000000;          // compile error: balance has private access in IDCard
card.charge(4.50);               // allowed: a public mutator that checks the amount

Terminology:

private means only IDCard can touch balance. Everyone else goes through accessors (getBalance) and mutators (charge), so the checks inside charge cannot be skipped.


Code Runner Challenge

Fix the three bugs without renaming anything, then run it. Expect: Maya 3

View IPYNB Source
// CODE_RUNNER: Run it, then uncomment card.balance = 1000000; and see what the compiler says
// Private Fields and Public Accessors / Mutators
public class IDCard {
    private String owner;
    private double balance;

    public IDCard(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    public String getOwner() { return owner; }       // accessor
    public double getBalance() { return balance; }   // accessor

    public boolean charge(double amount) {           // mutator with a guard
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
}

public class Kiosk {
    public static void main(String[] args) {
        IDCard card = new IDCard("Maya", 10.00);
        System.out.println("coffee: " + card.charge(4.50) + " -> " + card.getBalance());
        System.out.println("laptop: " + card.charge(999.00) + " -> " + card.getBalance());

        // This would cause an error:
        // card.balance = 1000000;   // NOT ALLOWED: balance has private access in IDCard
    }
}

Kiosk.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Popcorn Hack

2-minute challenge: Locker has all three traps in it. Fix each one so the program prints Maya 3, without renaming any variable.

  1. The constructor assigns a parameter to itself
  2. store re-declares the field as a local
  3. A commented-out line would use a loop variable after the loop (leave it commented and explain why)

After it prints Maya 3, add a comment above each fixed line saying which variable the broken version touched.

Code Runner Challenge

Fill in the blanks, then run it

View IPYNB Source
// CODE_RUNNER: Fix the three bugs without renaming anything, then run it. Expect: Maya 3
// Practice #1 - Try it yourself first!
public class Locker {
    private String owner;
    private int items;

    public Locker(String owner) {
        owner = owner;                 // Bug 1: which owner is on each side of the = ?
        items = 0;
    }

    public void store(int count) {
        int items = this.items;        // Bug 2: is this the field or a new variable?
        for (int i = 0; i < count; i++) {
            int added = 1;
            items += added;
        }
        // System.out.println(added);  // Bug 3: why can this line never compile? Leave it commented.
    }

    public String getOwner() { return owner; }
    public int getItems() { return items; }

    public static void main(String[] args) {
        Locker l = new Locker("Maya");
        l.store(3);
        System.out.println(l.getOwner() + " " + l.getItems());
    }
}

Locker.main(null);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

MCQ Check

4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your notes.

Homework Hack

Task: Build a Player class for a game. Store the name and score as private fields, write a constructor whose parameters have the same names as the fields (so you must use this), write a getScore accessor, and write an addPoints mutator that rejects negative amounts. Then, from a separate Game class, try to change the score both ways and print the results.

Solution Skeleton:

// CODE_RUNNER: Fill in the blanks, then run it
public class Player {
    // 1. Two private fields: name (String) and score (int)

    // 2. Constructor: parameters must be named name and score, so use this.
    public Player(String name, int score) {

    }

    // 3. Accessor for score
    public int getScore() {
        return 0;
    }

    // 4. Mutator: add points only if amount > 0, return whether it was accepted
    public boolean addPoints(int amount) {
        return false;
    }
}

public class Game {
    public static void main(String[] args) {
        Player p = new Player("Maya", 10);
        System.out.println("start: " + p.getScore());              // 10
        System.out.println("add 5: " + p.addPoints(5));            // true
        System.out.println("add -50: " + p.addPoints(-50));        // false
        System.out.println("end: " + p.getScore());                // 15
        // p.score = 9999;   // 5. Uncomment once: what does the compiler say? Then comment it again.
    }
}

Game.main(null);

References

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf

Kaczmarczyk, L. C., Petrick, E. R., East, J. P., & Herman, G. L. (2010). Identifying student misconceptions of programming. In Proceedings of the 41st ACM Technical Symposium on Computer Science Education (pp. 107–111). Association for Computing Machinery.

Oracle. (n.d.). Using the this keyword. The Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Oracle. (n.d.). Controlling access to members of a class. The Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

All Java lessons