Unit 3 Cycle 2 Day 18: Scope Error: Local vs Instance

Unit 3 Advanced (Cycle 2) Day 18 of 28 Advanced

Scope Error: Local vs Instance

Section 3.9 — Scope and Access

Key Concept

A scope error with local versus instance variables occurs when a method declares a local variable with the same name as an instance variable. Inside that method, the local variable shadows the field. Assigning to the local variable does not change the instance variable. This is a common bug: void setX(int val) { int x = val; } creates a new local x instead of assigning to this.x. The AP exam presents subtle versions of this error where the shadowing is not immediately obvious.

Consider the following class.

public class Timer { private int seconds; public Timer(int s) { seconds = s; } public void tick() { int seconds = this.seconds - 1; } public int getSeconds() { return seconds; } }

After executing Timer t = new Timer(10); t.tick(); System.out.println(t.getSeconds());, what is printed?

Answer: (B) 10

The tick() method declares a LOCAL variable seconds that shadows the instance variable. The local variable gets 9, but the instance variable is unchanged. getSeconds() returns the instance variable: 10.

Why Not the Others?

(A) The instance variable is never modified. The local variable shadows it.

(C) The instance variable retains its original value of 10.

(D) The code compiles. Local variables can have the same name as instance variables (shadowing).

Common Mistake

Declaring a local variable with the same name as an instance variable creates shadowing. The local variable hides the field. To modify the field, use this.seconds or do not redeclare.

AP Exam Tip

Variable shadowing is a common AP exam trap. If a local variable and instance variable share a name, the local takes precedence without this.

Review this topic: Section 3.9 — Scope and Access • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.