Java
Scope
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 here
Method 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).
Exercise 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.
Show example solution
static int counter = 0;
static void increment() {
counter++;
System.out.println(counter);
}
// inside main:
increment();
increment();
increment();
Test yourself
-
Match declaration place to scope
- 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
-
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
Show answer
Yes, it spreads to the whole class — Local variables live only in their own method.
-
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
}
Show answer
static void f() {
for (int i = 0; i < 3; i++) {
int t = i * 2;
}
// t burada geçerli geçerli DEĞİL
}
Next lesson: Summary - Methods