Careeroza
Variable Scope
Where a Variable Lives
A variable is visible only inside the block { } where it is declared, from the line of declaration to the closing brace. This is its scope.
Example
public class Main {
static int visits = 0; // class level: visible in all methods
static void visit() {
visits++;
int local = 5; // only inside visit()
System.out.println("visit " + visits + ", local " + local);
}
public static void main(String[] args) {
visit();
visit();
int x = 10; // method scope
if (x > 5) {
int y = 20; // block scope: only inside this if
System.out.println(x + y);
}
// System.out.println(y); // error: cannot find symbol y
for (int i = 0; i < 2; i++) {
System.out.println("loop i = " + i);
}
// i is not visible here either
System.out.println("total visits " + visits);
}
}Output
visit 1, local 5 visit 2, local 5 30 loop i = 0 loop i = 1 total visits 2
Scope Levels
| Kind | Declared | Visible |
|---|---|---|
| Class (static/instance) variable | inside the class, outside methods | whole class |
| Local variable | inside a method | from declaration to end of method |
| Block variable | inside if, loop, { } | only inside that block |
| Parameter | in the method header | whole method |
Note: Local variables have no default value and must be initialised before use. Class variables get defaults (0, false, null).