Unit 3 · 15 min

3.8 Scope and Access

Every variable has a home block; outside that block, its name means nothing.

Summary, objectives and course and exam description (CED) codes

A local variable is declared in the header or body of a block of code and can only be used inside that block. Parameters of constructors and methods are local variables too, so they cannot be declared public or private. When a local variable or parameter has the same name as an instance variable, the name refers to the local variable inside that method or constructor.

By the end of this session you can

  • 3.8.A Explain where variables can be used in the code.

3.8.A3.8.A.13.8.A.2

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. Local variables live inside their block

Local variables are variables declared in the header or body of a block of code. A block is code between { and }, such as a method body, a loop or an if. A local variable can only be accessed in the block where it is declared 3.8.A.1.

public class Rainfall
{
    public static int total(int days)
    {
        int sum = 0;
        for (int day = 1; day <= days; day++)
        {
            int rain = day * 2;
            sum += rain;
        }
        return sum;
    }
}
System.out.println(Rainfall.total(3));

Output:

12
Variable Declared in Can be used
days the method header (parameter) anywhere in total
sum the method body from its declaration to the end of total
day the for loop header only inside the loop
rain the loop body only inside the loop body

Using a loop variable after the loop does not compile:

int sum = 0;
for (int day = 1; day <= 3; day++)
{
    sum += day;
}
System.out.println(day);

Compiler says:

error: cannot find symbol

Watch out: if you need the value after the loop, declare the variable before the loop, in the outer block.

2. Parameters are local variables

Constructors and methods are blocks of code, so their parameters are local variables too 3.8.A.1. A parameter can only be used inside its own constructor or method 3.8.A.1.

public class Thermometer
{
    private double celsius;

    public void setCelsius(double degrees)
    {
        celsius = degrees;
    }

    public double getFahrenheit()
    {
        return degrees * 9 / 5 + 32;
    }
}

Compiler says:

error: cannot find symbol

degrees exists only inside setCelsius. The second method must use the instance variable celsius, which every method of the class can use.

Local variables, including parameters, cannot be declared public or private 3.8.A.1. Access modifiers are only for the members of a class: instance variables, constructors and methods.

public class Profile
{
    private int age;

    public void setAge(private int newAge)
    {
        age = newAge;
    }
}

Compiler says:

error: modifier private not allowed here

3. Instance variables vs local variables

Instance variable Local variable or parameter
Declared in the class, outside every method and constructor in a block, a method header or a constructor header
Can be used in every constructor and method of the class only inside its block, constructor or method 3.8.A.1
public/private yes (usually private) never 3.8.A.1
Lifetime as long as the object exists only while the block runs

4. Same name: the local variable wins

When a local variable or parameter has the same name as an instance variable, the name refers to the local variable, not the instance variable, inside that constructor or method 3.8.A.2. The instance variable is “shadowed”.

This constructor looks right but does nothing useful:

public class Student
{
    private String name;
    private int grade;

    public Student(String name, int grade)
    {
        name = name;     // parameter = parameter
        grade = grade;   // parameter = parameter
    }

    public String toString()
    {
        return name + " (grade " + grade + ")";
    }
}
Student s = new Student("Lina", 10);
System.out.println(s);

Output:

null (grade 0)

Both assignments copy a parameter into itself (println shows the object through its toString method, which is background: writing toString is outside the AP® exam). The instance variables keep their default values, null and 0. Two fixes:

  • Give the parameters different names: public Student(String studentName, int studentGrade) with name = studentName;.
  • Use the keyword this to name the instance variable: this.name = name; (see topic 3.9).
public class Student
{
    private String name;
    private int grade;

    public Student(String studentName, int studentGrade)
    {
        name = studentName;
        grade = studentGrade;
    }

    public String toString()
    {
        return name + " (grade " + grade + ")";
    }
}
Student s = new Student("Lina", 10);
System.out.println(s);

Output:

Lina (grade 10)

5. A new local variable hides the instance variable

The same rule catches students who add a type in front of an instance variable name inside a method. That declares a new local variable 3.8.A.2.

public class Gamer
{
    private int score;

    public Gamer(int start)
    {
        score = start;
    }

    public void reset()
    {
        int score = 0;   // new local variable, not the instance variable
    }

    public int getScore()
    {
        return score;
    }
}
Gamer g = new Gamer(75);
g.reset();
System.out.println(g.getScore());

Output:

75

The fix is to remove the type: score = 0; assigns to the instance variable.

Lock it in: memory hooks

  • ScopeA variable lives from its declaration to the closing brace of the block it was born in.
  • ShadowingThe closest name wins: inside a method, a local or parameter hides the instance variable with the same name.
  • Access modifierspublic and private are for class members (instance variables, constructors, methods), never for locals.

Common misconceptions

  • "A variable declared in a for loop header can be used after the loop."

    Not quite. The loop variable is local to the loop. After the loop's closing brace it no longer exists, and using it is a compile error (cannot find symbol).

  • "Writing name = name; in a constructor stores the parameter in the instance variable."

    Not quite. Inside the constructor, name means the parameter, so the statement copies the parameter into itself. The instance variable keeps its default value (null for a String).

  • "Parameters can be made private to protect them."

    Not quite. Parameters and other local variables can never be declared public or private. They already exist only inside their method or constructor.

Exam traps

  • name = name; compiles but does nothing useful: look for it in constructors and setters.
  • int score = 0; inside a method creates a new local variable; it does not reset the instance variable score.
  • A variable declared inside an if block cannot be used after the if.
  • The loop variable of a for loop cannot be printed after the loop.

2PracticeRecall it, then check yourself

In 30 seconds

  1. Local variables are declared in the header or body of a block and can only be used in that block.
  2. Constructors and methods are blocks, so their parameters are local variables.
  3. Local variables and parameters cannot be declared public or private.
  4. Instance variables can be used in every constructor and method of the class.
  5. A local variable or parameter with the same name as an instance variable hides it inside that method or constructor.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Scope and Access

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.8.A.2
    public class Pet
    {
        private String name;
        private int age;
    
        public Pet(String name, int a)
        {
            name = name;
            age = a;
        }
    
        public String info()
        {
            return name + " " + age;
        }
    }
    
    Pet p = new Pet("Rex", 3);
    System.out.println(p.info());
    Show answer

    Answer: B. Inside the constructor, name refers to the parameter, because a parameter with the same name as an instance variable hides it. So name = name; copies the parameter into itself and the instance variable keeps its default value null. The parameter a has a different name, so age = a; correctly sets the instance variable to 3.

  2. 2 Consider the following method. Which of the following can replace /* missing code */ without causing a compile-time error? 3.8.A.1
    public static int countEvens(int n)
    {
        int count = 0;
        for (int k = 1; k <= n; k++)
        {
            if (k % 2 == 0)
            {
                int last = k;
                count++;
            }
        }
        /* missing code */
    }
    Show answer

    Answer: C. count is declared in the method body, so it can be used until the end of the method. k is declared in the for loop header and last inside the if block, so both stop existing at the end of their blocks, and using either one after the loop causes a cannot find symbol error.

  3. 3 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.8.A.1, 3.8.A.2
    public class Lamp
    {
        private int brightness;
    
        public Lamp(int b)
        {
            brightness = b;
        }
    
        public void dim(int amount)
        {
            int brightness = amount;
            brightness = brightness / 2;
        }
    
        public int getBrightness()
        {
            return brightness;
        }
    }
    
    Lamp lamp = new Lamp(80);
    lamp.dim(40);
    System.out.println(lamp.getBrightness());
    Show answer

    Answer: A. int brightness = amount; declares a new local variable that hides the instance variable inside dim. The local becomes 20 and disappears when the method ends, so the instance variable is still 80. The option 20 assumes the method changed the instance variable, and 40 assumes the parameter was stored.

  4. 4 In the Lamp class from the previous question, which of the following statements about the parameter amount is true? 3.8.A.1
    Show answer

    Answer: D. Methods are blocks of code, so their parameters are local variables that may only be used within that method. Local variables cannot be declared public or private. Other methods of the class cannot see amount, and it is created again with a new value on every call.

  5. 5 A Book class has the instance variable private String title; and the following constructor, which does not set the instance variable. Which change makes the constructor set title to the value of its parameter? 3.8.A.2
    public Book(String title)
    {
        title = title;
    }
    Show answer

    Answer: B. Inside the constructor, title means the parameter. this.title names the instance variable of the object being constructed, so this.title = title; stores the parameter in it. title = this.title; copies the other way, a parameter cannot be declared private (it does not compile), and making the instance variable public does not change which variable the name title refers to.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Scopetap to flip

    The part of a program where a variable can be used, set by the block in which the variable is declared.

    Example and CED codes
  • Local variabletap to flip

    A variable declared in the header or body of a block of code, including a method or constructor parameter, usable only in that block.

    Example and CED codes
  • Instance variabletap to flip

    An attribute declared in a class outside any method or constructor, whose value is unique to each object of the class.

    Example and CED codes
  • Parametertap to flip

    A variable declared in the header of a method or constructor. It receives the value passed in and can be used in the body.

    Example and CED codes
  • Access modifiertap to flip

    The keywords public and private, which control whether classes, data, constructors and methods can be used from outside the declaring class.

    Example and CED codes
  • thistap to flip

    A special variable inside an instance method or constructor that holds a reference to the current object, the object whose method or constructor is running.

    Example and CED codes
  • Variabletap to flip

    A named storage location that holds a value, which can change while the program runs. Every variable has a name and a data type.

    Example and CED codes

Questions students ask

What is scope in Java?

Scope is the part of the program where a variable can be used. A local variable can only be used in the block where it is declared; an instance variable can be used throughout its class.

Is a parameter a local variable?

Yes. Constructors and methods are blocks of code, so their parameters are local variables that can only be used inside that constructor or method.

Why does my instance variable stay null after the constructor runs?

The constructor parameter probably has the same name as the instance variable. Inside the constructor the name refers to the parameter, so name = name; never touches the instance variable. Rename the parameter or write this.name = name;.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure