Variable Scope
Overview
Variable scope determines exactly *where* in your code a variable can be seen and used. If you create a variable inside a specific method, it belongs ONLY to that method. The rest of the program has no idea it exists.
Why does Java do this? For security and clean memory! If every variable was visible everywhere, it would be pure chaos. Variables would accidentally overwrite each other all the time. Scope acts like a privacy fence around your code blocks.
1. Block Scope (The curly braces {})
The golden rule of scope in Java: A variable is born when it is declared inside a pair of curly braces `{}`. When the code execution leaves those curly braces, the variable is instantly destroyed.
2. Method Scope
Variables created inside a method (local variables) cannot be accessed by other methods. They are private to that method.
3. Class Scope (Instance Variables)
Variables declared at the very top of a Class, outside of any methods, belong to the whole class. Any method inside that class can see and use them.
Syntax
Notice how variables die as soon as their block `{}` ends.
public class ScopeExample {
// Class Scope: Visible to every method in this class
static int globalScore = 100;
public static void main(String[] args) {
// Method Scope: Visible only inside main()
int localScore = 50;
if (localScore > 10) {
// Block Scope: Visible ONLY inside this 'if' block
boolean isWinner = true;
System.out.println(isWinner);
} // 'isWinner' is instantly destroyed right here!
// System.out.println(isWinner); // ❌ ERROR! Java says: What is 'isWinner'?
}
}Common Pitfalls
- Trying to use a variable outside of the loop or if-statement it was created in.
- Declaring a variable with the same name twice in the same scope.
Interview Tips
- Understand 'Variable Shadowing'. This happens when you have a Class variable and a Method variable with the exact same name. The Method variable 'shadows' (hides) the Class variable.
Real-World Example
Scope is crucial for keeping temporary data from leaking into the rest of the application.
public class ATM {
private double totalBankVaultMoney = 1000000.0; // Class scope
public void withdraw(double amount) {
// 'fee' is only needed temporarily for this specific transaction.
// It has method scope, so it doesn't clutter the rest of the class.
double fee = 2.50;
System.out.println("Dispensing: " + amount);
totalBankVaultMoney = totalBankVaultMoney - (amount + fee);
}
}