The switch statement

A sequence of if-else-else that compares a single value against several constant values can be replaced with a switch statement.

Syntax:
switch(expression)
{
   case val1:
        // action1
        break;
   case val2:
        // action2
        break;
    case val3:
        // action3
        break;
...
    default:
        //defaultAction
        break;
}

If the value of expression is vali, then actioni is executed. The default case is optional, but if it is included and expression does not match any vali, then the defaultAction is executed.

Note: Each branch of the switch is terminated with a break statement. If the break is missing, we will not fall out of the switch structure after an action is executed.

The expression must be of type int or char.

Example:
int k;
...
switch(k)
{
   case 0: System.out.println("zero"); break;
   case 1: System.out.println("one"); break;
   case 2: System.out.println("two"); break;
   case 3: System.out.println("three"); break;
   default: System.out.println("integer is not in [0, 3]"); break;
}

This code is a shortcut for:
int k;
...
if(k == 0) System.out.println("zero");
else if (k == 1) System.out.println("one");
else if (k == 2) System.out.println("two");
else if (k == 3) System.out.println("three");
else System.out.println("integer is not in [0, 3]");


Example:
int k;
...
switch(k)
{
    case 0: System.out.print("zero"); break;
    case 1: System.out.print("one"); // oops - missing break
    case 2: System.out.print("two"); break;
    ...
}

If k is equal to 1, then the statement after the case 1: label is executed. But since there is no break, the statement after the case 2: label is also executed. This code will print "onetwo".



Exercise: Write a code segment that reads an integer value from the user, and prints the corresponding month. That is, if the value is 1, print January; if it's 2, print February, and so on. If the integer is not between 1 and 12, print "Invalid month".