Skip to main content
Engineering LibreTexts

6.11: The switch Multiway Selection Structure

  • Page ID
    58028
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Another selection structure to add to our repertoire is the switch/break structure. It is meant to provide a shorthand way of coding the following type of multiway selection structure:

    if (integralVar == integralValue1)
         // some statements
    else if (integralVar == integralValue2)
         // some statements
    else if (integralVar == integralValue3)
         // some statements
    else // some statements

    Note that each of the conditions in this case involves the equality of an integral variable and an integral value. This type of structure occurs so frequently in programs that most languages contain statements specially designed to handle it. In Java, we use a combination of the switch and break statements to implement multiway selection.

    The switch is designed to select one of several actions depending on the value of some integral expression:

    switch (integralExpression)
    {  case integralValue1:
           // some statements
       case integralValue2:
           // some statements
       case integralValue3:
           // some statements
       default:
           some statements
    }

    The integralExpression must evaluate to a primitive integral value of type byte, short, int, char, or boolean. It may not be a long, float, double, or a class type. The integralValues must be literals or final variables. They serve as labels in the one or more case clauses that make up the switch statement body. The default clause is optional, but it is a good idea to include it.

    A switch statement is executed according to the following rules:

    The integralExpression is evaluated.

    Control passes to the statements following the case label whose value equals the integralExpression or, if no cases apply, to the default clause.

    Beginning at the selected label or at the default, all of the statements up to the end of the switch are executed.

    Consider the following example:

    int m = 2;
    switch (m)
    {  case 1:
          System.out.print(" m = 1");
       case 2:
          System.out.print(" m = 2");
       case 3:
          System.out.print(" m = 3");
       default:
          System.out.print(" default case");
    }

    In this case, because m equals 2, the following output would be produced:

     m = 2 m = 3 default case

    Obviously, this output does not match the following if-else multiway selection structure, which would output, simply, m = 2:

    int m = 2;
    if (m == 1)
         System.out.print(" m = 1");
    else if (m == 2)
         System.out.print(" m = 2");
    else if (m == 3)
         System.out.print(" m = 3");
    else
         System.out.print(" default case");

    The reason for this disparity is that the switch executes all statements following the label that matches the value of the integralExpression (see again Rule 3 on the previous page).

    In order to use the switch as a multiway selection, you must force it to break out of the case clause after executing that clause’s statements:

    int m = 2;
    switch (m)
    {  case 1:
           System.out.print(" m = 1");
           break;
       case 2:
           System.out.print(" m = 2");
           break;
       case 3:
           System.out.print(" m = 3");
           break;
       default:
           System.out.print(" default case");
    }

    In this example, the break statement causes control to pass to the end of the switch, with the effect being that one and only one case will be executed within the switch. Thus, the output of this code segment will be simply , matching exactly the behavior of the multiway if-else selection structure (Fig. [fig-multiwayswitch]).

    Identify any errors in the following switch structures (if there is no error, specify the output):

    (a) int k = 0;
        switch (k)
        case 0:
            System.out.println("zero");
            break;
        case 1:
            System.out.println("one");
            break;
        default:
            System.out.println("default");
            break;
    (b) int k = 0;
        switch (k + 1)
        {   case 0:
                System.out.println("zero");
                break;
            case 1:
                System.out.println("one");
                break;
            default:
                System.out.println("default");
                break;
        }
    (c) int k = 6;
        switch (k / 3.0)
        {   case 2:
                System.out.println("zero");
                break;
            case 3:
                System.out.println("one");
                break;
            default:
                System.out.println("default");
                break;
        }

    Flavors of ice cream are represented as integers where 0 is vanilla, 1 is chocolate, and 2 is strawberry. Write a switch statement that checks an integer variable flavor and prints out the name of the ice cream flavor or prints “Error” in the default case.

    Modify your solution to the previous exercise to use constants (final variables) to represent the ice cream flavors.


    This page titled 6.11: The switch Multiway Selection Structure is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.