I found this case a bit peculiar:
int x = 1;
switch(x){
case 0 :
boolean b = false;
break;
case 1 :
b = true; //will compile just right
System.out.println(b); //will print true
break;
default:
System.out.println(b); //will not compile
}
I just think this is confusing. Local variables are said to be accessible within the entire block of codes. Sure, b
is within a switch block so I can understand it is accessible in a different case, even though this seems to contradict the switch flow that it may not go through the first case, and therefore, may not declare and initialize b
.
But isn't this again contradicting if b
meanwhile is still inaccessible in the default branch?
Is there any special execution for local variable declarations in a case branch that it will run whether the case has been matched or not? If yes, then why can't default branch access it?
Edit for the duplicate flag: The question here is not about how the variable declared in a case branch is not local (as I noted above), but instead, why the local variable declared inside a case is accessible outside it, but not the value it has been initialized with.
Found a similar question that I believe answers my question: Declaring and initializing variables within Java switches