AP Computer Science A · Unit 3 lecture · Part 8 of 10 · 7 min

3.8 Scope and accessScope: where a variable lives

Mr. Thompkins
This section is short, but it explains a bug that has fooled every programmer I know at least once: a variable that changes, and then the change disappears.

A variable's scope is the part of the code where its name can be used. Variables declared inside a method or constructor, including inside a loop or an if, are local variables. A local variable exists from the line that declares it to the closing brace of the block around it, and then it's gone. Parameters are local too: they belong to their method and disappear when it returns. Instance variables are different: they live as long as their object and can be used in every constructor and instance method of the class.

?Wait, what counts as a block?
A block is any code between a matching pair of braces: a method body, a loop body, an if or else body. A variable declared in a for header, like int k, belongs to that loop's block.
Kind of variableDeclaredCan be usedExists until
Instance variableIn the class, outside every methodIn every constructor and instance methodThe object is gone
Static variableIn the class, with staticEverywhere in the classThe program ends
ParameterIn a method or constructor headerOnly inside that methodThe method returns
Local variableInside a method, loop or other blockFrom its declaration to the closing }Its block ends
Four kinds of variables and how long each one lives.
1for (int k = 0; k < 3; k++)12{3    int sq = k * k;24}5System.out.println(sq);3
  1. line 1 k exists only in the loop
  2. line 3 sq is born and dies on every pass
  3. line 5 error: cannot find symbol (variable sq)
output › compile error: cannot find symbol
sq and k both die when the loop ends.

The fix for that error is to declare the variable before the loop, where it will still exist afterward: int sq = 0; above the for, then sq = k * k; inside. Rule of thumb: declare a variable in the smallest block that still covers every place you use it.

Now the sneaky part. If a local variable or a parameter has the same name as an instance variable, then inside that method the name means the local one. The local variable shadows the instance variable, and the instance variable is hidden there.

1public class Tally2{3    private int total;145    public void addRange(int low, int high)6    {7        int total = 0;28        for (int k = low; k <= high; k++)9        {10            total += k;311        }12    }1314    public int getTotal() { return total; }15}16// in a client class17Tally t = new Tally();18t.addRange(1, 4);19System.out.println(t.getTotal());
  1. line 3 The instance variable total starts at 0
  2. line 7 A local variable with the same name hides it
  3. line 10 Adds to the local total, which vanishes at line 12
output › 0
A local total hides the instance variable total.
Pause and think
Predict the output before you read it under the code. Then say how to fix addRange.
I thought about it. Show me
It prints 0. Inside addRange, int total = 0; creates a local variable, and the loop adds 1 + 2 + 3 + 4 = 10 into that local, which vanishes when the method ends. The instance variable never changed. Fix: delete int, so the line becomes total = 0; or remove that line if the tally should keep adding across calls.
Repair the tally
The author wants addRange to add every integer from low to high onto the running total, across calls. Fix the class, then predict what t.getTotal() returns after t.addRange(1, 4); and t.addRange(10, 10);
  1. Remove the line int total = 0; completely. Now total in the loop means the instance variable.
    Why?
    Writing total = 0; instead would reset the tally on every call, which breaks "across calls".
  2. addRange(1, 4) adds 1 + 2 + 3 + 4 = 10. total is 10.
  3. addRange(10, 10): the loop runs once with k = 10, so total becomes 20.
    Why?
    k <= high includes high, so a range from 10 to 10 runs exactly once.

Answer: Delete int total = 0;. After both calls, getTotal() returns 20.

Stuck? Get a hint
  1. Which line creates a second variable named total?
  2. Without it, the loop changes the instance variable.
  3. Does the loop include high itself?
?Wait, then why can Tank's pourInto use other.liters?
Scope and access are different questions. Scope asks where a name exists. Access (public or private) asks which classes may use it. liters is private to the Tank class, and pourInto is inside the Tank class, so it may use liters on any Tank, including other.
Check yourself
What is the result of running this code segment?
int count = 0;
for (int i = 1; i <= 3; i++)
{
    int doubled = i * 2;
    count += doubled;
}
System.out.println(count + " " + i);
  1. A12 4
  2. B12 3
  3. C6 4
  4. DNothing: the code does not compile
Show the answer

D. i is declared in the for header, so it exists only inside the loop. Using it in the last line is a compile error: cannot find symbol. The first choice is the trap: if i were declared before the loop it would end at 4, and count is 2 + 4 + 6 = 12, but the code never gets to run.

  • Local variables and parameters exist only inside their block or method.
  • Instance variables exist as long as the object and are usable in all its instance methods.
  • A local variable or parameter with an instance variable's name shadows it inside that method.
  • A line that starts with a type always declares a new variable.