Scope and Switch Statements
You'll learn: How variable declarations inside switch cases affect visibility and scope across different branches.
The Unusual Scope Rule in Switch Statements
Unlike if statements or loops, a traditional switch statement treats all cases as part of the same scope. This means when you declare a variable in one case, it's visible in all subsequent case blocks—even ones you might never execute!
Think of a switch as a single room with multiple labeled doorways. Once you enter through one door (a matching case), you can see everything declared anywhere in that room, not just near your entry point.
The Problem
int day = 2;
switch (day) {
case 1:
int message = 100; // Declared here
break;
case 2:
message = 200; // Visible here! (but not initialized if case 1 was skipped)
System.out.println(message);
break;
}
This compiles because message is visible in case 2, but it's dangerous—if you enter at case 2, message was never initialized!
The Solution: Block Scope with Braces
To create case-local scope, wrap each case's code in braces:
int day = 2;
switch (day) {
case 1: {
int message = 100; // Local to this block only
System.out.println(message);
break;
}
case 2: {
int message = 200; // Different variable, no conflict
System.out.println(message);
break;
}
}
Now each case has its own separate scope, preventing accidental variable sharing and allowing you to reuse variable names safely.
Key Takeaway: Variables declared in switch cases are visible in all following cases unless you create case-local scope by wrapping each case in braces {}.