Variable Scope in Java
A variable's scope is the region of code where it can actually be referenced by name, and in Java, scope is determined by where a variable is declared relative to curly braces — a variable declared inside a block only exists from that point until the closing brace of that same block. A variable declared inside a for loop's parentheses, or inside an if's block, or inside a method, is entirely invisible outside of it; trying to reference it after its block ends is a compile error, not a runtime one.
Two variables with the same name can coexist in a program as long as their scopes don't overlap — a variable named count inside one method and a completely different variable also named count inside another method never conflict, since neither method's block can see into the other's.
Block scope
A variable declared inside braces exists only from that declaration until that same block's closing brace.
Method-local variables
Parameters and variables declared directly inside a method exist only for that method's own execution.
Loop-variable scope
A variable declared in a for loop's initializer exists only inside that loop, including its condition and update clauses.
Nested blocks can see outward, not inward
Code inside an if's block can reference variables declared in the surrounding method, but not the other way around.
Non-overlapping scopes can reuse names
Two variables with the same name in genuinely separate scopes, like two different methods, don't conflict with each other at all.
public class ScopeDemo { static void printRange() { for (int i = 0; i < 3; i++) { int doubled = i * 2; System.out.println(doubled); } } public static void main(String[] args) { printRange(); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.