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.
Reviewed against the CED on
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)withname = studentName;. - Use the keyword
thisto 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
- Local variables are declared in the header or body of a block and can only be used in that block.
- Constructors and methods are blocks, so their parameters are local variables.
- Local variables and parameters cannot be declared public or private.
- Instance variables can be used in every constructor and method of the class.
- 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.
3PrevailLock it in for exam day
By the numbers
- Kinds of local variable two kinds CED 3.8.A.1
- variables declared in the header or body of a blocksuch as a loop or method body
- parameters of constructors and methods
- Where each kind of variable can be used three kinds CED 3.8.A.1, 3.8.A.2
- instance variablein every constructor and method of the class
- parameteronly in its own constructor or method
- local variableonly in its block, after its declaration
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;.