Consider this code:
int num = 0;
switch(num) {
case 1:
boolean bool = false;
break;
case 2:
String one;
String two;
String three;
//..simulating lots of vars
break;
default:
bool = true;
System.out.println(bool);
break;
}
Since we were allowed to reference a variable declared in another case, this means that even though case 1
wasn't chosen, boolean bool
was still declared.
Since default
is the last option, and java works from left to right (top to bottom), I'm assuming that the variables in case 2
(and any other cases) will also be declared.
This make me think that the more code you have in the cases declared before the case chosen, the longer it'll take to actually access that case compared to if the chosen case was declared first.
Is there a specific reason switch statements work this way? And wouldn't it be best to use if-else
rather than switch statements if there are a lot of cases? (talking processing time, nano-seconds)
{ } represents a scope and you could use it in any way you like.
In a switch statement:
switch (...) {
}
Everything inside the { } belongs in the same scope. If you want to have the cases have their own scope, you need to use { } like this:
switch (...) {
case 0: {
}
break;
case 1: {
}
break;
}
Similarly, you can use { } do declare scopes within scopes like this:
{
{
int i;
}
{
int i;
}
}
Switch statements in Java were patterned after switch statements in C++ were patterned after switch statements in C were probably patterned after switch statements in B ... BCPL (which certainly has the same single-block structure) ...
As a long lost Sun bug report says (about something else), 'the reasons are lost in the mists of time'.
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