The switch statement (multi-way switch)

  1. Syntax of the switch statement of Java (C/C++):

    
          switch ( integer expression )
          {
             case integer_constant1: statements      
             case integer_constant2: statements      
    	 ...
             default: statements      
          }
    
    

    The value of the integer expression is matched agaist the list of integer constants.

    If a match is found (equal), then all statements following the case label are executed until a break is reached.

    If no match is found, and a default clause is provided, then the statements following the default label are executed. (But if no default clause was provided, the switch will not do anything if no match was found)

  2. Example:

    Example: switch statement
        int digit;
        String digitName;
        ....
        switch ( digit )
        {
           case 1: digitName = "one";   break;     
           case 2: digitName = "two";   break;
           case 3: digitName = "three"; break;
           case 4: digitName = "four";  break;
           case 5: digitName = "five";  break;
           case 6: digitName = "six";   break;
           case 7: digitName = "seven"; break;
           case 8: digitName = "eight"; break;
           case 9: digitName = "nine";  break;
           case 0: digitName = "zero";  break;
           default: digitName = "";
        }
    

    is equivalent to:

    Example: switch statement
        int digit;
        String digitName;
        ....
        if ( digit == 1 )
           digitName = "one";
        else if ( digit == 2 )
           digitName = "two";
        else if ( digit == 3 )
           digitName = "three";
        else if ( digit == 4 )
           digitName = "four";
        else if ( digit == 5 )
           digitName = "five";
        else if ( digit == 6 )
           digitName = "six"; 
        else if ( digit == 7 )
           digitName = "seven";       
        else if ( digit == 8 )
           digitName = "eight";
        else if ( digit == 9 )
           digitName = "nine";
        else if ( digit == 0 )
           digitName = "zero";
        else
           digitName = "";
        }
    

  3. Remarks

    The if statement is an essential programming construct (essential means that some programs CANNOT be written without using it)

    A switch can always be replaced by a nested if statement

    The switch construct does NOT enhance the expressive power of a programming language

    In other words: The switch statement is NOT essential