I'm preparing for Java7 Oracle certificate and I'm wondering why Java handles switch-case in such a weird way:
public static void main(String[] args) {
int a = 2;
switch (a) {
case 0:
//System.out.println(b); // cannot find symbol variable b
break;
case 1:
boolean b=false;
break;
case 2:
b = true; // how case knows about existence of variable b?
break;
case 3:
//System.out.println(b); // var b might not have been initialized
break;
}
}
That's obvious why case 0 and case 3 inform about unknown symbol or uninitialized variable, but I can't imagine why case 2 is working properly? How compiler knows about the type of b
if it's assigned in case 1? For me that's not coherent.
UPDATE1: Actually what is even more weird is that in case 3 I noticed compile time error (Linux64, Java7 and Java8), but some of my colleagues do not.
I prepared very simple maven project: https://github.com/gonciarz/switch-test
UPDATE2: It seems that for everyone case3 does not compile. Thank you guys for your clarifications.