Java Scope
Scope determines where a variable can be accessed in your code. Local variables declared inside a method exist only within that method, while instance variables belong to an object and exist as long as the object does.
Variables declared inside a block (like a for loop or if statement) are only visible within that block.
class C {
int instanceVar; // instance scope
void m() {
int localVar; // local scope
}
}Local vs instance scope
Local variables live inside methods and are destroyed when the method returns. Instance variables belong to an object and live as long as the object does.
Block scope
Variables declared inside {} braces, such as inside a loop, are only accessible within that block.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
int local = i * 10;
System.out.println(local);
}
}
}0
10local and i are only accessible inside the for loop block.
Key points
- Local variables exist only inside their method or block.
- Instance variables exist as long as the object exists.
- Block-scoped variables cannot be accessed outside their braces.
- Scope helps avoid naming conflicts.
