Big idea: A variable only exists inside the block where it was declared. When a local name matches an instance variable, the local one wins.
Learning objectives
Explain where variables can be used in the code.
Local scope
Local variables are declared inside a method, constructor, or block (including loop headers). They exist only within that block. Parameters are local variables of their method. Local variables never get public or private.
Code
int total = 0;
for (int i = 0; i < 3; i++) {
int sq = i * i;
total += sq;
}
// System.out.println(i); // compile error: i is out of scope// System.out.println(sq); // compile error: sq is out of scopeSystem.out.println(total);
Output
5
Shadowing
If a parameter or local variable has the same name as an instance variable, that name refers to the local one inside the method. The instance variable is shadowed. A setter that writes width = width; just assigns the parameter to itself.
Code
Rectangle r = newRectangle(2, 5);
r.badSetWidth(10);
System.out.println(r.area());
r.setWidth(10);
System.out.println(r.area());
Output
10
50
Key points
Local variables (including parameters) can only be used in the block where they are declared.
Local variables can't be declared public or private.
A local name that matches an instance variable shadows it inside that method.
Watch out
Shadowing is a common reason a setter "does nothing." Use a different name or this.width.
Quick check
Where can a variable declared in a for-loop header be used?Show answer