The switch expression

A switch expression is the same choice with a value. It is written with an arrow after each label, it never falls through, and the compiler checks that every possible selector value is covered. It arrived as a preview in Java 12, became final in Java 14, and in Java 21 a switch is both a statement and an expression.

Arrow labels

The arrow form replaces case X: with case X ->. The body is one expression, one statement or one block, and the end of the body ends the branch: there is no fall-through and no break. The whole switch is then an expression whose value is the value of the chosen body.

The file Arrows.java:

public class Arrows { public static void main(String[] args) { int day = 6; String name = switch (day) { case 1, 7 -> "weekend"; case 2, 3, 4, 5, 6 -> "weekday"; default -> "not a day"; }; System.out.println(day + ": " + name); } }

javac -Xlint:all Arrows.java
java Arrows

6: weekday

The value of the switch is assigned to name, and the semicolon after the closing brace ends the statement, not the switch. The default is required here because the selector is an int and its values are not limited to a known set.

Several constants per label

A label may list any number of constants separated by commas, and they all run the same body. That replaces the old trick of empty labels stacked above a shared branch, and it removes the fall-through warning that came with it: the two weekend days are one label, not two labels and an accident waiting to happen.

The constants of one label must be different, and a duplicate is a compile error rather than a surprise at run time. The compiler also refuses a constant that does not fit the selector type, so a case "one" under an int is reported at the label.

Blocks and yield

A body that needs more than one statement is a block, and a block gives its value with yield. The word is a keyword inside a switch expression; return would leave the whole method, which is not what a branch means.

public class Yield { public static void main(String[] args) { int month = 2; int days = switch (month) { case 1, 3, 5, 7, 8, 10, 12 -> 31; case 4, 6, 9, 11 -> 30; case 2 -> { int result = 28; yield result; } default -> throw new IllegalArgumentException("month " + month); }; System.out.println("days: " + days); } }

javac -Xlint:all Yield.java
java Yield

days: 28

The default branch throws instead of yielding, because an invalid month has no number of days. A switch expression whose branches all throw, or all return, is still exhaustive: the compiler cares that every path leaves the switch, not that every path produces a value on the same line.

An exhaustive switch over an enum

An enum has a fixed set of constants, so a switch that names every one of them is exhaustive and needs no default. That is the useful half of the rule: add a constant to the enum and the compiler reports every switch that forgot it, at the switch rather than in a test much later.

public class EnumSwitch { enum Size { SMALL, MEDIUM, LARGE } public static void main(String[] args) { Size size = Size.MEDIUM; int price = switch (size) { case SMALL -> 5; case MEDIUM -> 8; case LARGE -> 12; }; System.out.println(size + ": " + price); } }

javac -Xlint:all EnumSwitch.java
java EnumSwitch

MEDIUM: 8

The class declares the enum inside itself, which is legal because only the outer class is public. An enum used by several classes gets a file of its own, and the compiler then checks every switch in the project against the same list of constants.

Statement against expression

The old form is still a statement and still falls through; the arrow form is an expression and never does. A statement switch may use arrows too, and then it behaves like a series of exclusive branches with no value. A switch expression must produce a value on every path, so it must be exhaustive: a default, or every constant of an enum.

A missing branch is a compile error at the switch, not a run-time default:

public class NotExhaustive { public static void main(String[] args) { int n = 2; int value = switch (n) { case 1 -> 10; }; System.out.println(value); } }

javac -Xlint:all NotExhaustive.java

NotExhaustive.java:4: error: the switch expression does not cover all possible input values
int value = switch (n) {
^
1 error

Exercises

  1. Rewrite Days.java from the previous lesson with arrow labels and no break.
  2. Add a TINY constant to the enum in EnumSwitch.java and build it before you add a branch. What does javac say?
  3. Give the case 2 block in Yield.java a second statement that changes result before the yield.
  4. Turn NotExhaustive.java into a statement switch on the same value. Does it compile now?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an arrow label change about a switch branch?

    Answer

    The branch never falls through to the next label

    The body of an arrow label is exclusive: its end ends the branch.

  2. What gives the value of a block in a switch expression?

    Answer

    yield

    yield passes a value out of the switch expression; return would leave the method.

  3. When is a switch expression allowed to have no default?

    Answer

    When its selector is an enum and every constant has a label

    An enum has a closed set of constants, so covering all of them is exhaustive; every branch throwing also leaves no path without a value.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int day = 1; String name = switch (day) { case 1, 7 -> "weekend"; case 2, 3, 4, 5, 6 -> "weekday"; default -> "not a day"; }; System.out.println(name); } }

    Answer

    weekend

    The label lists both 1 and 7, and the selector is 1.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int month = 4; int days = switch (month) { case 4, 6, 9, 11 -> 30; default -> 31; }; System.out.println(days); } }

    Answer

    30

    April is in the 30-day label, so the first branch is chosen.

  6. What does this program print? public class Q3 { public static void main(String[] args) { int n = 5; String text = switch (n) { case 1 -> "one"; case 5 -> { String value = "five"; yield value; } default -> "many"; }; System.out.println(text); } }

    Answer

    five

    The block sets a local string and yields it, so the switch value is five.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { int n = 2; int value = switch (n) { case 1 -> 10; }; System.out.println(value); } }

    Answer

    error: the switch expression does not cover all possible input values

    An int selector has values outside the labels, and the expression has no default.

  8. What does this program print? public class Q5 { enum Color { RED, GREEN, BLUE } public static void main(String[] args) { Color color = Color.BLUE; int code = switch (color) { case RED -> 1; case GREEN -> 2; case BLUE -> 3; }; System.out.println(code); } }

    Answer

    3

    Every constant of the enum has a label, so the switch is exhaustive and BLUE gives 3.

  9. Can two constants of the same label be equal?

    Answer

    No, a duplicate constant is a compile error

    The compiler refuses a duplicate case constant in the same switch.

  10. Which form can fall through into the next label?

    Answer

    case X: with no break

    The colon form falls through without break; the arrow form never does.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev