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
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.
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.
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
thisseparates an instance variable from a same-named parameter. - Identify the object
thisrefers to during a call. - Determine the effect of passing
thisas 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
- "
thisrefers to the class."
Where can each kind of variable be used?
| Kind | Declared | Scope | Lasts |
|---|---|---|---|
| Instance variable | in the class, outside every method | every constructor and instance method of the class | as long as the object |
| Parameter | in a method or constructor header | that whole body | one call |
| Local variable | inside a body or block | from its declaration to the end of its block | until 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
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
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
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
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.
Step 1: List each variable's scope.
Variable Declared In scope on lines limitline 1 2 to 13 countline 3 3 to 13 kline 4 4 to 11 doubledline 6 6 to 11 WhyA local variable lasts from its declaration to the closing brace of its block;
doubled's block closes on line 11.Step 2: Check every use.
Line 12 uses
doubled, which is out of scope there; every other use is inside its range.WhyAn 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.
Step 1: Trace the calls.
Call thisChange or result new Box(2, 3)smallwidth2,height3new Box(4, 5)bigwidth4,height5small.grow(2)smallthis.width= 2 + 2 = 4small.fitsInside(big)small4 < 4 is falsesmall.area()small4 × 3 = 12 WhyIn
grow,this.widthissmall's instance variable andwidthis the parameter 2.Step 2: Build the line.
fitsInsidereturnsfalsebecause the first comparison fails, so&&stops there.WhyEqual 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.
Step 1: Match
add's header.addis aTeammethod taking aPlayer, so it is called ontwith the current player,this.WhyOnly
t.add(this)has the right object before the dot and the right type inside the parentheses.Step 2: Reject the others.
A calls
addon aPlayer, which has noadd. C passes aTeamwhere aPlayeris needed. D calls an instance method on the class name.WhyEach breaks one rule, so each fails to compile.
Step 3: Trace.
a.join(t)addsa: size 1, total 12.b.join(t)addsb: size 2, total 42.WhyIn each call,
thisis 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());
Step 1: Trace
update(3).The local
readingis 6. It shadows the instance variable, sothis.readingis needed to reach the instance variable: 10 + 6 = 16.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
- Recall What is the scope of a local variable declared inside the body of a
forloop?
- 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.
- 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.
- 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
wordends 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
wordis in the other's scope.
- 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 andadd(1)makes 15. total = 0;changes only the parameter.
- Exam-style
Personhasprivate int height;. Which body forpublic boolean isTaller(Person other)returnstruewhen the person the method is called on is taller thanother?
- 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
intwith aPersonreference, which does not compile.
- 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),thisisa, sob's partner is set toa. c'spartnerwas never set, so it keeps its default,null.
- Exam-style What value does
rhold 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:
clicksis an instance variable, so it reaches 3 on the third call.sessionis local, so it is 1 on every call: 3 × 10 + 1 = 31.
- Apply Using the
Boxclass from worked example 2, what dothisandotherrefer to during the callbig.fitsInside(small)?
- A)
thisissmallandotherisbig - B) Both refer to
big - C)
thisis theBoxclass andotherissmall - D)
thisisbigandotherissmall
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
smallis copied intoother. - C treats
thisas 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.
thisis the object the method was called on;this.xis always the instance variable.- Passing
thishands another method a reference to the current object.