Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Flow Control and Exception Handling - switch Statement

Syntax (JLS §14.10)

    switch( expression ) {
        case value1:
            statement1;
            break;
        case value2:
            statement2;
            break;
        case value3:
            statement3;
            break;
        ...
        case valuen:
            statement n;
            break;
        default:
            statements;
    }
  • transfers control depending on the value of an expression
  • the type of the expression must be byte, char, short or int
  • case labels must be constant expressions capable of being represented by the switch expression type
Watch for mismatching case constants!
    char c;
    
    switch( c ) {
        case 'a':
        case 'b':
        case "c":       // String, not character!
        case 'd':    
    }
  • no two case constant expressions may be the same
  • the default case does not have to be at the end of the code block
  • if no case matches the expression, the default case will be executed
  • if break is omitted between case blocks the code will fallthrough, continuing to execute statements until a break statement or the end of the switch block is encountered

Example Code

Tips

  • you do not have to have a default statement
  • the default statement can appear anywhere in the construct, does not have to be last

Traps

  • using an expression vs a value promotable to int
  • duplicate case values
  • case statements with wrong type
  • missing break statements

Statements if switch for while do
Labels Exceptions Handling Exceptions try-catch-finally