This is a very interesting conundrum, because in a "default" branch, the variable b is not in scope anymore. I haven't found an explicit resolution for this in the JLS, but if I reaaaaaly want, then I can interpret section 16.9.2 (Definite Assignment and Statements / switch Statements) in a way that it fits. I would have expected to find it explicitly in 6.3-2 (Scope of Local Variable Declarations) or in 14.11 (Blocks and Statements / The switch Statement).
The real mindboggling things start here:
Code: Select all
public static void main(String args[]) {
switch(Integer.parseInt(args[0])) {
case 0: var b = false; System.out.println(b);
case 1: b = true; System.out.println(b);
default : System.out.println(args);
case 2: b = false; System.out.println(b);
}
}
Running with 0 it prints: false, true, args@hash, false (with 1: true, args@hash, false) BUT b is not defined in the default branch! i.e., s.o.p(b); is a compile time error in the line of default
@admin: this also means that the explanation text for "Compile time error at line //3", namely "There is no problem here. b is in scope for the rest of the switch block" is semi-correct: it is correct for the exact example given in the question, but 100% correct it would be "There is no problem here. b is in scope for every case-labeled block for the rest of the switch block (not for default though)."