2.3 The switch Statement
When you are testing a value and need to branch many ways on that value, a long chain of else if becomes verbose. A switch can make the structure clearer.
switch (op) {
case '+':
System.out.println(a + b);
break;
case '-':
System.out.println(a - b);
break;
default:
System.out.println("Unsupported");
break;
}A switch matches the value in the parentheses against each case. Once a case matches, execution starts from there.
switch works with types such as byte, short, int, char, String, and enums. It cannot directly switch on double.break and fall-through
break exits the switch. If you forget it, execution continues into the following case, a behavior called fall-through.
Sometimes you can use fall-through deliberately so several cases share the same code:
switch (grade) {
case 'A':
case 'B':
System.out.println("Pass");
break;
case 'C':
System.out.println("Just pass");
break;
default:
System.out.println("Fail");
break;
}Here 'A' and 'B' share one output, because 'A' has no break and falls through to 'B'. Most of the time, however, a missing break is a bug, so be careful.
default
default handles every case that did not match, similar to the else in an if-else if-else. It is good practice to always include default, even if it only prints a message, so the program behaves predictably on unexpected input.