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
The key point is that the default case means: no other case was taken.
The switch construct allows you to have local variables within its overall scope, but still each "read" must see a prior "write".
And the compiler can easily detect that the default case didn't see a initialization for b.
Beyond that, the reason why you can have such assignments in different cases is: the overall switch statement only has one "switch block".
See the Java Language Spec for further details!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With