Course outline · 0% complete

0/29 lessons0%

Course overview →

switch

lesson 3-2 · ~5 min · 8/29

Choosing among many values

Real code constantly maps one code to one outcome: an HTTP status number to a message, a menu keypress to an action, a day number to a name. When one variable decides among many fixed options, a chain of else if statements gets noisy and easy to typo.

switch handles that case directly, and modern Java, version 14 and later, has a clean arrow form:

String day = switch (dayNumber) {
  case 1 -> "Monday";
  case 2 -> "Tuesday";
  case 6, 7 -> "Weekend";
  default -> "Unknown";
};

Each case value -> picks one branch, default catches everything else, and the whole switch can produce a value you assign. Note the trailing statement terminator after the closing brace, because this is an assignment rather than a block.

You will also meet the older colon-and-break form in legacy code, where forgetting break makes execution fall through into the next case. Prefer arrows in new code.

What switch can and cannot switch on

switch works on int, char, String, and enums, which are types whose values form a set of fixed labels the compiler can compare exactly.

It does not work on double, since 0.1 + 0.2 lands near 0.3 and never exactly on a case label. It also cannot express ranges, because score >= 90 has no case form, so grading bands stay with if and else if.

Several labels can share one branch, and a String switch reads well for command parsing:

String role = switch (command) {
  case "add", "a" -> "adding";
  case "quit", "q" -> "quitting";
  default -> "unknown command";
};
SituationUse
exact labels, one variableswitch
ranges or compound conditionsif and else if

A switch that produces a value also has to be exhaustive, which is why default is effectively required. The compiler refuses a switch that could fall off the end with nothing to assign.

A day-number lookup

Seven day numbers mapped to five names plus a shared weekend branch.

public class Main {
  public static void main(String[] args) {
    int dayNumber = 3;
    String day = switch (dayNumber) {
      case 1 -> "Monday";
      case 2 -> "Tuesday";
      case 3 -> "Wednesday";
      case 4 -> "Thursday";
      case 5 -> "Friday";
      case 6, 7 -> "Weekend";
      default -> "Unknown";
    };
    System.out.println(day);
  }
}

Output

Wednesday

Setting dayNumber to 7 prints Weekend, because 6 and 7 share one branch, and setting it to 9 prints Unknown through default.

Written as else if this would be eleven lines of repeated dayNumber == comparisons. The switch states the variable once, which removes an entire category of typo.

Fall-through in the colon form

In the old colon-style switch, a case with no break statement runs its own code and then continues into the next case as well.

This is fall-through. Execution keeps going into the following case even though its label did not match:

switch (n) {
  case 1:
    System.out.println("one");
    // no break, so "two" prints as well
  case 2:
    System.out.println("two");
    break;
}

With n at 1 that prints both lines. Fall-through is occasionally deliberate, for grouping labels, but far more often it is a forgotten break, and it is a famous source of bugs.

The arrow form never falls through, which is the main reason to prefer it in new code.

A switch on a char

Char literals use single quotes, so the labels are written case 'A' ->.

public class Main {
  public static void main(String[] args) {
    char grade = 'B';
    String message = switch (grade) {
      case 'A' -> "excellent";
      case 'B' -> "good";
      case 'C' -> "passing";
      default -> "see instructor";
    };
    System.out.println(message);
  }
}

Output

good

The switch produces a String, so it is assigned to message, and the closing brace is followed by a statement terminator because the whole thing is one assignment statement.

default covers every other grade, including lowercase letters. A char switch is case-sensitive, so 'b' would fall to default, which is worth remembering when the value comes from typed input.