Scope
- Java course
- Beginner
- Lesson 75/116
- 4 min
Learn variable scope inside methods.
Scope: where does a variable live?
A variable is valid inside the block where it is declared. This is called its scope. When the block closes, the variable disappears.
static void f() {
int x = 5;
System.out.println(x); // x is valid here
}
// x is NOT valid hereMethod parameters also belong to their method; another method cannot reach them. In nested blocks, the outer block variables are visible in the inner block, but not the other way around.
Name clash and shadowing
You cannot declare a variable in an inner block with the same name as one in the outer block; this is a compile error. But if a method parameter shares a name with a class variable, the parameter shadows the class variable.
static int x = 10; // class variable
static void f(int x) {
System.out.println(x); // parameter x
}To avoid confusion, keep names distinct. To reach the class variable, you use this.x (you will see this later).
Practice Local and class variable
Declare static int counter = 0; at class level. The increment method should increase counter by 1 each time it is called and print the new value. Call increment three times from main.
Starter code
public class Main {
// Define a class-level counter variable starting at 0
public static void main(String[] args) {
// Call the increment method three times
}
// Define the static void increment method
}Sample solution
static int counter = 0;
static void increment() {
counter++;
System.out.println(counter);
}
// inside main:
increment();
increment();
increment();Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match declaration place to scope
| Term | Meaning |
|---|---|
Inside a method |
Valid through the method |
Method parameter |
Only in the method body |
Inside a for loop |
In the loop block |
Top of the class |
In all methods |
2 Can a variable declared in one method be reached from another?
- No, the variable is local to that method
- Only if declared public
- Yes, but only from static methods
- Yes, it spreads to the whole class Correct answer
Explanation: Local variables live only in their own method.
3 Fill in the blank: block scope
static void f() {
for (int i = 0; i < 3; i++) {
int t = i * 2;
}
// t burada ____ geçerli DEĞİL
}
static void f() {
for (int i = 0; i < 3; i++) {
int t = i * 2;
}
// t burada geçerli geçerli DEĞİL
}
Explanation: t is not valid outside the loop block.