Java Scope
Scope is the region of a program where a variable can be used. A variable declared inside a block can be used only inside that block.
A block variable works inside its block
The variable secret lives inside the if block. The print line sits inside the same block, so the value prints.
public class Main {
public static void main(String[] args) {
if (true) {
int secret = 42;
System.out.println(secret);
}
}
}A block variable fails outside its block
The print line sits after the if block. The variable no longer exists there, and the compiler refuses the line.
public class Main {
public static void main(String[] args) {
if (true) {
int secret = 42;
}
System.out.println(secret);
}
}Same name, two methods
Each method declares its own value variable. Each print shows the copy from its own method.
public class Main {
static void first() {
int value = 10;
System.out.println(value);
}
static void second() {
int value = 20;
System.out.println(value);
}
public static void main(String[] args) {
first();
second();
}
}Example
public class Main {
public static void main(String[] args) {
int total = 5;
if (true) {
int bonus = 3;
total = total + bonus;
System.out.println(total);
}
System.out.println(total);
}
}Key points
- A block is code inside a pair of curly braces.
- A variable declared in a block exists only in that block.
- Code after the block cannot use that variable.
- A variable declared in a method exists only in that method.
- Two methods can each hold a variable with the same name.
- Each method sees only its own copy of that name.
In this example, total is declared in main before the if block. The block adds bonus to total and prints 8. The last line prints total again and shows 8, because total lives in main and not in the block.
Note
A variable declared outside a block can be used inside the block.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
Where can a variable declared inside a block be used?