All topics
library
beginner

Variable Scoping & Shadowing

Know how Java resolves variable names when local, instance, and class-level variables share the same name.

Variable scoping in Java follows lexical (block) scoping rules. A variable is visible from its declaration point to the end of the enclosing block. When names collide across scopes, the innermost scope wins — this is called shadowing.

Like nested Russian dolls: open the smallest one first (local scope). If the name isn't there, open the next bigger one (instance scope), then the next (class scope).

Key Concepts

1
Types of shadowing: 1. Local variable shadows instance field: common in constructors/setters. Resolve with this.fieldName. 2. Instance field shadows static field: rare. Resolve with ClassName.staticField. 3. Parameter shadows field: same as local variable shadowing. 4. Lambda parameter shadows enclosing variable: NOT allowed since Java 8 — compile error.
2
Scope levels (inner to outer): - Block scope: for-loop variable, try-catch parameter - Method scope: parameters, local variables - Instance scope: instance fields (accessed via this) - Class scope: static fields (accessed via ClassName)
3
Key rules: - You cannot declare two local variables with the same name in overlapping scopes. - You CAN shadow an instance field with a local variable (but shouldn't without good reason). - Enhanced for-loop and try-with-resources variables are block-scoped. - Switch expression variables are scoped to their case branch (since Java 14).
4
Interviewers often test this with constructor puzzles: what does name refer to when there's a parameter name and a field name?