I have several switch statements in a Java program. My question is, if I construct the switch statement similar to this:
switch (getNum()) {
case 0: // do something
case 1: // do something
...
}
where the variable to be switched is getting returned from an accessor method (aka ‘getter’ method), will the switch statement call getNum() every time it checks a case? Or will it assign a temporary variable to the int being returned from getNum() to check each case?
It doesn’t ‘check each case’ at all. It evaluates the expression once and jumps to the associated case immediately, via one of several techniques depending on the implementation.
It doesn’t do that either: see above.