AP® Computer Science A · Unit 3 · Topic 3.8
Scope, Shadowing, and Where a Variable Lives
Scope is the region of code where a variable's name can be used, and it's defined by the braces it's declared inside. When two variables share a name, the innermost one wins — this is shadowing.
Every variable belongs to the block where it's declared — the stretch of code between one opening brace and its matching closing brace. The moment the program's execution passes that closing brace, the variable is gone: its memory is reclaimed and its name means nothing anymore. This is why a counter declared inside a for loop's header, like for (int i = 0; i < 10; i++), can't be used after the loop ends — i was born in the loop's scope and dies with it.
Scopes can nest, and when they do, the innermost one wins. If a method has a parameter named score, and the class also has an instance variable named score, writing plain score inside that method refers to the parameter. The parameter shadows the instance variable because it's closer — more local — to the code reading it. To reach the shadowed instance variable anyway, you write this.score, which explicitly asks for the object's field rather than the local name.
This is also why a static method can never see an instance variable, no matter what it's named. Instance variables live inside objects — each object gets its own copy when it's constructed. A static method belongs to the class itself, not to any particular object, so when it runs there's no object around for an instance variable's name to point to. This connects directly to why constructors and instance methods can freely use this: they always have an object attached, and static methods simply don't.
Key terms
- Scope
- The region of code, bounded by braces, where a variable's name can be referenced.
- Shadowing
- When a more local variable shares a name with a less local one, hiding the outer one from plain use.
- Instance variable
- A field that belongs to a specific object, with its own separate copy in every instance of the class.
- Static method
- A method that belongs to the class itself and runs without any object, so it has no this.
Watch it explained
- How it worksHow does each pair of braces open and close a region where a name is visible?
- Worked exampleTrace a counter declared inside a for header and find exactly where it stops existing.
- Worked exampleFind which variable wins when a parameter has the same name as an instance variable.
- Common mistakeWhy isn't an instance variable in scope inside a static method?
Check yourself
End of topic.