"switch" related practice questions..

practice makes perfect!

Here is how a switch statement defined in the Java Language Specification:
SwitchStatement:
    switch ( Expression ) SwitchBlock
 
SwitchBlock:
    { SwitchBlockStatementGroupsopt SwitchLabelsopt }
 
SwitchBlockStatementGroups:
    SwitchBlockStatementGroup
    SwitchBlockStatementGroups SwitchBlockStatementGroup
 
SwitchBlockStatementGroup:
    SwitchLabels BlockStatements
 
SwitchLabels:
    SwitchLabel
    SwitchLabels SwitchLabel
 
SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :
 
EnumConstantName:
    Identifier
  • What are the allowed types for Expression to be evaluated?  (tip: 10 possible types!)
  • Will the following compile? If not, what is wrong?
class SwitchRelated {
    void mySwitch(final int foo) {
        final int bar = 0;
        final int baz;
        baz = 1;
 
        switch (foo) {
            case bar:
                // do nothing
                break;
            case baz:
                // do nothing
                break;
        }
    }
}
  • Will the following compile? If not, why not?
class SwitchRelated {
    void mySwitch(byte foo) {
        switch (foo) {
            case 128:
                // do nothing!
                break;
        }
    }
}
void switchNull() {
    final Integer foo = null;
    switch (foo) {
        default:
            break;
    }
}

How does a typical switch statement get executed?

  • If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence.
  • If no case matches but there is a default label, then all statements after the matching default label in the switch block, if any, are executed in sequence.
  • If no case matches and there is no default label, then no further action is taken.