Block Scope and Variable Lifetime
What You'll Learn
You'll discover that variables declared inside curly braces {} only exist within those braces and vanish when the block ends.
Understanding Block Scope
In Java, scope determines where a variable can be accessed. Every pair of curly braces {} creates a block, and any variable declared inside that block lives only within it.
Think of a block like a temporary workspace: tools (variables) you create inside that workspace disappear once you leave. The moment execution exits the closing }, those variables are destroyed.
Where Blocks Appear
Blocks exist in many structures you've already learned:
if,else, andelse ifstatementswhileanddo-whileloopsforloops (including the loop body)switchstatements
Why This Matters
if (temperature > 30) {
int warning = 1; // 'warning' exists ONLY in this block
System.out.println(warning);
}
// 'warning' no longer exists here - compiler error if you try to use it
The variable warning is born when the if block executes and dies when that block ends. You cannot access warning outside those braces.
Nested Blocks
Inner blocks can see outer block variables, but not vice versa:
int outer = 10; // visible everywhere below
if (outer > 5) {
int inner = 20; // only visible in this if block
System.out.println(outer); // ✓ works
System.out.println(inner); // ✓ works
}
System.out.println(outer); // ✓ works
System.out.println(inner); // ✗ error - inner is gone
Key Takeaway: Variables declared in a block {} are destroyed when that block ends—they cannot be accessed outside their enclosing braces, ensuring clean, predictable code behavior.