AP · Computer Science A · Anatomy of a Class

Scope and the this Keyword

15 min readUpdated December 1, 2026FreeAP Computer Science A, Class Creation

A variable's scope is the part of the code where its name can be used: an instance variable throughout its class, a parameter throughout its method, and a local variable from its declaration to the closing brace of its block. Inside an instance method or constructor, this refers to the current object, so this.size always means the instance variable, and passing this as an argument hands the current object to another method.

Quick check

  1. A constructor's parameter is called name, and so is an instance variable. Why does name = name; leave the instance variable unset?Show answerHide answer

    Inside the constructor the parameter shadows the instance variable, so both sides mean the parameter.

  2. Inside a method, what kind of variable does int total = 0; declare?Show answerHide answer

    A local variable: it belongs to that method call only.

  3. Can code after a for loop use the variable i declared in the loop's header?Show answerHide answer

    No. The loop variable's scope ends with the loop.

Know these already? Jump to the practice questions

What you'll be able to do

  • State the scope of each kind of variable.
  • Determine whether a variable can be used on a given line.
  • Explain how this separates an instance variable from a same-named parameter.
  • Identify the object this refers to during a call.
  • Determine the effect of passing this as an argument.

Key terms

Scope

The region of code in which a variable's name can be used.

In plain English
Where a variable is visible.
Don't write
"A variable can be used anywhere in the class once it is declared."

Local variable

A variable declared inside a method, constructor or block. It exists from its declaration to the end of that block and is created fresh on every call.

In plain English
A scratch variable that disappears when its block ends.
Don't write
"A local variable keeps its value between calls."

this

A reference to the current object: the object whose method or constructor is running.

In plain English
"Me", from the object's point of view.
Don't write
"this refers to the class."

Where can each kind of variable be used?

KindDeclaredScopeLasts
Instance variablein the class, outside every methodevery constructor and instance method of the classas long as the object
Parameterin a method or constructor headerthat whole bodyone call
Local variableinside a body or blockfrom its declaration to the end of its blockuntil the block ends

So two methods can each have a local count with no clash. A local or parameter may share a name with an instance variable; the nearer one then shadows it.

Access is a separate idea: private limits which classes can use a member, while scope limits which lines can use a variable. Code inside a class may even read the private instance variables of another object of that class, as in other.width.

Check yourself

Can a method of the class use a private instance variable that is declared below the method in the file?
Show answerHide answer

Yes. An instance variable's scope is the whole class, wherever in it the declaration sits.

What happens to variables declared inside a block or loop?

A block is code between { and }. A variable declared inside one disappears at its closing brace.

public int sumSquares(int n)
{
    int total = 0;
    for (int i = 1; i <= n; i++)
    {
        int sq = i * i;
        total = total + sq;
    }
    return total;
}

total is declared before the loop, so it survives the loop and can be returned. i exists only inside the for statement, and sq only inside the loop body, made fresh on each pass. Writing return total + sq; would not compile, because sq is out of scope after the loop.

Within its scope, a local variable's name cannot be declared again: a second int total inside the loop is a compile-time error. Two separate blocks, such as the if and else branches, may each declare their own variable with the same name.

Key idea

To keep a value after a block ends, declare its variable before the block.

Check yourself

In sumSquares, which variables can the return statement use?
Show answerHide answer

total and n. i and sq are out of scope.

What does this mean, and when do you need it?

Inside an instance method or constructor, this is a reference to the object the method was called on. In small.grow(2), this is small; in big.grow(2), it is big.

You need this when a parameter or local variable has the same name as an instance variable. The plain name means the nearer variable; this.name always means the instance variable.

public void grow(int width)
{
    this.width = this.width + width;
}

Here this.width is the instance variable and width alone is the parameter. When no name clashes, width and this.width mean the same variable, so this. is optional.

this exists only where there is a current object, so a static method cannot use it.

Check yourself

During big.grow(3), which object's width does this.width change?
Show answerHide answer

The object big refers to.

Why pass this as an argument?

Sometimes an object must hand itself to another method, such as a player joining a team. Passing this gives the other method a reference to the current object.

public void join(Team t)
{
    t.add(this);
}

When a.join(t) runs, this is a, so t.add receives a reference to a. Because it is a reference, not a copy, the team can call a's methods and see its current state.

Check yourself

Inside b.join(t), what does t.add(this) pass?
Show answerHide answer

A reference to the object b refers to.

Worked example 1: Find the out-of-scope variable

Question: This method does not compile. Which line causes the error?

1: public int countBig(int limit)
2: {
3:     int count = 0;
4:     for (int k = 1; k <= 10; k++)
5:     {
6:         int doubled = k * 2;
7:         if (doubled > limit)
8:         {
9:             count++;
10:        }
11:    }
12:    return count + doubled;
13: }

What tells you the method

A compile error in a method with nested blocks, so mark where each variable's scope starts and ends.

  1. Step 1: List each variable's scope.

    VariableDeclaredIn scope on lines
    limitline 12 to 13
    countline 33 to 13
    kline 44 to 11
    doubledline 66 to 11
    Why

    A local variable lasts from its declaration to the closing brace of its block; doubled's block closes on line 11.

  2. Step 2: Check every use.

    Line 12 uses doubled, which is out of scope there; every other use is inside its range.

    Why

    An out-of-scope name is an unknown symbol to the compiler.

Check it

Changing line 12 to return count; makes it compile, and countBig(14) then returns 3, for k = 8, 9 and 10.

Answer

Line 12

Worked example 2: Trace this and a parameter with the same name

Question: What is printed?

public class Box
{
    private int width;
    private int height;

    public Box(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public int area()
    {
        return width * height;
    }

    public boolean fitsInside(Box other)
    {
        return this.width < other.width && height < other.height;
    }

    public void grow(int width)
    {
        this.width = this.width + width;
    }
}
Box small = new Box(2, 3);
Box big = new Box(4, 5);
small.grow(2);
System.out.println(small.fitsInside(big) + " " + small.area());

What tells you the method

Parameters share names with instance variables, so track what this and each plain name mean in every call.

  1. Step 1: Trace the calls.

    CallthisChange or result
    new Box(2, 3)smallwidth 2, height 3
    new Box(4, 5)bigwidth 4, height 5
    small.grow(2)smallthis.width = 2 + 2 = 4
    small.fitsInside(big)small4 < 4 is false
    small.area()small4 × 3 = 12
    Why

    In grow, this.width is small's instance variable and width is the parameter 2.

  2. Step 2: Build the line.

    fitsInside returns false because the first comparison fails, so && stops there.

    Why

    Equal widths do not fit: the test is strictly less than.

Check it

Before grow, 2 < 4 and 3 < 5 would both hold, so the call to grow is what changed the result.

Answer

false 12

Worked example 3: Pass the current object

Question: Which body for join makes the team record the player join was called on?

public class Player
{
    private int score;

    public Player(int s)
    {
        score = s;
    }

    public int getScore()
    {
        return score;
    }

    public void join(Team t)
    {
        /* missing code */
    }
}
public class Team
{
    private int size;
    private int totalScore;

    public void add(Player p)
    {
        size++;
        totalScore = totalScore + p.getScore();
    }

    public String report()
    {
        return size + " players, " + totalScore + " points";
    }
}
Team t = new Team();
Player a = new Player(12);
Player b = new Player(30);
a.join(t);
b.join(t);
System.out.println(t.report());
  • A) this.add(t);
  • B) t.add(this);
  • C) t.add(t);
  • D) Team.add(this);

What tells you the method

The current object must be handed to another object's method, so this is an argument.

  1. Step 1: Match add's header.

    add is a Team method taking a Player, so it is called on t with the current player, this.

    Why

    Only t.add(this) has the right object before the dot and the right type inside the parentheses.

  2. Step 2: Reject the others.

    A calls add on a Player, which has no add. C passes a Team where a Player is needed. D calls an instance method on the class name.

    Why

    Each breaks one rule, so each fails to compile.

  3. Step 3: Trace.

    a.join(t) adds a: size 1, total 12. b.join(t) adds b: size 2, total 42.

    Why

    In each call, this is the player before the dot.

Check it

The report then reads "2 players, 42 points": two join calls ran, and 12 + 30 = 42.

Answer

B

Your turn

Question: What is printed?

public class Meter
{
    private int reading;

    public Meter(int r)
    {
        reading = r;
    }

    public void update(int extra)
    {
        int reading = extra * 2;
        this.reading = this.reading + reading;
    }

    public int getReading()
    {
        return reading;
    }
}
Meter m = new Meter(10);
m.update(3);
m.update(1);
System.out.println(m.getReading());
  1. Step 1: Trace update(3).

    The local reading is 6. It shadows the instance variable, so this.reading is needed to reach the instance variable: 10 + 6 = 16.

  2. Step 2: Your go: trace update(1), then the print.

Show the full solutionHide the solution

Step 2. A fresh local reading is 2, so the instance variable becomes 16 + 2 = 18. getReading() has no local reading, so it returns the instance variable, 18.

Answer: 18

Traps

Trap

A variable declared inside a loop or if block can be used after the block.

It seems right because the code is still in the same method. But the variable's scope ends at the block's closing brace, so using it later is a compile-time error.

Does for (int i = 0; i < 3; i++) { } followed by System.out.println(i); compile?

No: i is out of scope after the loop.

Trap

A local variable keeps its value between calls on the same object.

It seems right because the object stays the same. But a local variable is created fresh on every call; instance variables (and static variables) keep their values between calls.

public int tick() { int c = 0; c++; return c; } is called twice. What does the second call return?

1, the same as the first call.

What's examined

On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask which line fails because a variable is out of scope, what this refers to during a call, or what is printed when parameters share names with instance variables. In free response, you use this to set instance variables and declare each variable where it can reach every use.

Practice questions

  1. Recall What is the scope of a local variable declared inside the body of a for loop?
  • A) The whole method, including the lines before it
  • B) The whole class
  • C) From its declaration to the end of the loop body
  • D) From its declaration to the end of the method
Show answer

Answer: C. A local variable lasts until the closing brace of the block that declares it.

Why the others are wrong:

  • A treats it as visible before its declaration.
  • B describes an instance variable.
  • D ignores the loop body's closing brace.
  1. Recall Answer instance variable, parameter or local variable: which kind keeps its value between method calls on the same object?
Show answer

Answer: Instance variable

Marking points:

  • Parameters and local variables are created fresh on each call.
  1. Apply Give the number of the line that stops this method compiling.
1: public String label(int temp)
2: {
3:     if (temp > 30)
4:     {
5:         String word = "hot";
6:     }
7:     else
8:     {
9:         String word = "mild";
10:    }
11:    return word;
12: }
Show answer

Answer: Line 11.

Marking points:

  • Each word ends at its block's closing brace, on line 6 or line 10.
  • Lines 5 and 9 are legal: the two blocks are separate, so neither word is in the other's scope.
  1. Apply What is printed?
public class Tally
{
    private int total;

    public Tally(int total)
    {
        this.total = total * 2;
    }

    public void add(int total)
    {
        this.total = this.total + total;
        total = 0;
    }

    public int getTotal()
    {
        return total;
    }
}
Tally t = new Tally(5);
t.add(4);
t.add(1);
System.out.println(t.getTotal());
Show answer

Answer: 15

Marking points:

  • The constructor sets the instance variable to 5 × 2 = 10; add(4) makes 14 and add(1) makes 15.
  • total = 0; changes only the parameter.
  1. Exam-style Person has private int height;. Which body for public boolean isTaller(Person other) returns true when the person the method is called on is taller than other?
  • A) return height > other.height;
  • B) return other.height > this.height;
  • C) return this.height > this.height;
  • D) return height > other;
Show answer

Answer: A. height is the current object's, and code inside Person may read other.height even though it is private.

Why the others are wrong:

  • B has the comparison the wrong way round.
  • C compares the current object with itself, so it is always false.
  • D compares an int with a Person reference, which does not compile.
  1. Exam-style What is printed?
public class Dancer
{
    private String name;
    private Dancer partner;

    public Dancer(String name)
    {
        this.name = name;
    }

    public void pairWith(Dancer other)
    {
        partner = other;
        other.partner = this;
    }

    public String info()
    {
        if (partner == null)
        {
            return name + " alone";
        }
        return name + " with " + partner.name;
    }
}
Dancer a = new Dancer("Ana");
Dancer b = new Dancer("Ben");
Dancer c = new Dancer("Cai");
a.pairWith(b);
System.out.println(b.info());
System.out.println(c.info());
Show answer

Answer: Ben with Ana then Cai alone on the next line.

Marking points:

  • In a.pairWith(b), this is a, so b's partner is set to a.
  • c's partner was never set, so it keeps its default, null.
  1. Exam-style What value does r hold after this code runs?
public class Clicker
{
    private int clicks;

    public int click()
    {
        int session = 0;
        session++;
        clicks++;
        return clicks * 10 + session;
    }
}
Clicker k = new Clicker();
k.click();
k.click();
int r = k.click();
Show answer

Answer: 31

Marking points:

  • clicks is an instance variable, so it reaches 3 on the third call.
  • session is local, so it is 1 on every call: 3 × 10 + 1 = 31.
  1. Apply Using the Box class from worked example 2, what do this and other refer to during the call big.fitsInside(small)?
  • A) this is small and other is big
  • B) Both refer to big
  • C) this is the Box class and other is small
  • D) this is big and other is small
Show answer

Answer: D. this is the object before the dot, and the argument fills the parameter other.

Why the others are wrong:

  • A swaps the object and the argument.
  • B forgets that the argument small is copied into other.
  • C treats this as the class; it is always an object.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • Instance variables are visible in the whole class; parameters in their method; locals from declaration to the end of their block.
  • Declare a variable before a block if you need it after the block.
  • Locals start fresh on each call; instance variables persist.
  • this is the object the method was called on; this.x is always the instance variable.
  • Passing this hands another method a reference to the current object.

Keep learning

Prerequisites: Writing Constructors

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Class Creation

All Anatomy of a Class notes

Part of Novark's AP Computer Science A notes