4.1.3.3 Multiple Selection


Nested if-statements can become cumbersome when you have to deal with multiple selection with many alternatives. The switch control structure offers help in case the selection is against integer types but long and BigInteger, or against a char. The general format of the switch-statement is
switch (expression) {
  case constantExpression:
    statement;
    break;
  case constantExpression: 
    statement;
    break;
  .................
  default: 
    statement;
    break;
}
If a case matches the expression value, execution starts at that case. The optional case labeled default is executed if none of the other cases are satisfied. The break statement causes an immediate exit from the switch.

An example is the following application that looks at the first character of the first argument to know what to do next. It also illustrates that with absence of the break statement you can fall through several cases.

public class WhatToDO {
  public static void main(String[] args) {
    char c= args[0].charAt(0);
    switch(c) {
      case 'y':
      case 'Y':
        System.out.println("Yes");
        break;
      case 'n':
      case 'N':
        System.out.println("No");
        break;     
      case 'h':
      case 'H': 
      case '?':
        System.out.println("No help available");
        break;    
      default:
        System.out.println("Unknown command");
        break;
    }
  }
}
When you apply this application with the argument "y" and "Help", respectively, then you get the responses
Yes
No help available