The switch statement

The switch statement can be used instead of multiple if's in situations where the possibilities can be enumerated.

Example 8: The following sets the price based on watts:
   switch(watts) {
      case 40:  price = 0.50;
                break;
      case 60:  price = 0.69;
                break;
      case 75:  price = 0.85;
                break;
      case 100:
      case 150: price = 1;
                break;
      default:  price = 0;
                System.out.println("No bulb in stock.");
   }

Exercise 10: Convert the following if to a switch.

   if ( momOrDad == 'M' || momOrDad == 'm') 
      System.out.println("Happy Mother's Day"); 
   else if ( momOrDad == 'D' || momOrDad == 'd') 
      System.out.println("Happy Father's Day"); 
Ans:
   switch (momOrDad) { 
       case 'M':   
       case 'm':  System.out.println("Happy Mother's Day");
                  break; 
       case 'D': 
       case 'd':  System.out.println("Happy Father's Day"); 
                  break; 
    } 
The break must be put at the end of the clause or it continues through the clauses. For example, if the first break is omitted in the code of Exercise 10, an 'M' will cause both prints to be executed.

The only values that you may test when using a switch statement are ordinal values:

Note: no strings, floats, doubles etc.

Example 9: You may use a return instead of a break if appropriate.

   switch(watts) {
      case 40:  return 0.50; 
      case 60:  return 0.69; 
      case 75:  return 0.85; 
      case 100: 
      case 150: return 1; 
      default:  return 0; 
   }