If we have to realize a multiple-choice selection we can use several nested if-else statements. Java has also a specific statement that can be used in specific cases to realize in a simpler way a multiple-choice selection.
Syntax:
switch (expression){
case label-1: statements-1
break;
...
case label-n: statements-n
break;
default: default-statements}
Semantics:
Example:
int i; ... switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("less than zero or greater than two"); }
When i is equal to 0 (respectively, 1, 2) then "zero" (respectively "one", "two") is printed; when i is less than 0 or greater than two, then "less than zero or greater than two" is printed.
Note: If we have more than one values of the expression for which we want to execute the same statements, we can group together different cases:
case label-1: case label-2: statements
break;