Skip to content

5.4 switch Statements

Key terms: none introduced

5.4.1 Syntax and Semantics

Sometimes a program must choose among several alternatives based on the value of an expression. This can always be accomplished with an if-else chain, but when the same expression is compared against several possible values, a switch statement is often more compact and easier to read. The general syntax is:

switch (value) {
    case a -> // executed if value matches a
    case b -> // executed if value matches b
    case c -> // executed if value matches c
    // other cases
    default -> // executed if no case matches
}

The branch whose case label matches the switch value is selected for execution. The default branch is optional.

Listing 5.4.1 revisits the Craps example from Sections 5.2 and 5.3, using a switch statement instead of an if-else chain to determine the output with less code and equal clarity.

Listing 5.4.1 - ComeOutRoll.java

ComeOutRoll.java
package chap05.sect4;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Simulates the first roll in the game of Craps. The player rolls two dice and the outcome depends
 * on the sum: natural (7 or 11) - player wins; craps (2, 3, or 12) - player loses; otherwise, the
 * game continues according to a different rule.
 *
 * @author Drue Coles
 * @version 3.0 - uses both a switch statement and a switch expression for comparison
 */
public class ComeOutRoll {

   public static void main(String[] args) {
      ThreadLocalRandom rand = ThreadLocalRandom.current();
      int die1 = rand.nextInt(1, 7);
      int die2 = rand.nextInt(1, 7);
      final int comeOutRoll = die1 + die2;

      System.out.printf("You rolled %d + %d = %d. %n", die1, die2, comeOutRoll);

      final String winMessage = "Natural. You win.";
      final String loseMessage = "Craps. You lose.";
      final String continueMessage = "The game continues.";

      // switch statement
      switch (comeOutRoll) {
         case 7, 11 -> System.out.println(winMessage);
         case 2, 3, 12 -> System.out.println(loseMessage);
         default -> System.out.println(continueMessage);
      }

      // switch expression
      String result = switch (comeOutRoll) {
         case 7, 11 -> "Natural. You win.";
         case 2, 3, 12 -> "Craps. You lose.";
         default -> "The game continues.";
      };
      System.out.println(result);
   }
}

A switch can also be used as an expression. Unlike a switch statement, which performs an action, a switch expression produces a value. The second switch in Listing 5.4.1 illustrates the idea.