Scope in if Statements
What you'll learn: You'll discover why variables declared inside an if block disappear when that block ends.
What is Scope in if Statements?
When you declare a variable inside an if block's curly braces, that variable only exists within those braces. Once the closing brace } is reached, the variable is destroyed and cannot be accessed anymore—not in the else block, not in an else if, and not in any code that follows.
Why Does This Happen?
Think of an if block like a room with a door. Anything you create inside that room stays in that room. Once you step out (close the brace), you can't reach back in to grab what you left behind. This is called block scope—the variable's lifetime is limited to the block where it was declared.
Example of the Problem
if (temperature > 30) {
String message = "It's hot!";
System.out.println(message); // Works fine here
}
// message does not exist here anymore!
// System.out.println(message); // ERROR: cannot find symbol
If you need a variable in multiple branches or after the if statement, declare it before the if:
String message; // Declared outside, accessible everywhere below
if (temperature > 30) {
message = "It's hot!";
} else {
message = "It's cool.";
}
System.out.println(message); // Works! message exists here
The Key Principle
Variables live and die within their enclosing curly braces. An if block creates its own scope, and anything declared inside is trapped there.
Key Takeaway: Variables declared inside an if block exist only within that block—they cannot be accessed in else clauses or after the if statement ends. Declare variables outside the if if you need them elsewhere.