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)