Switch

The new switch is an expression; the old one falls through easily.

A classic switch on an int, an enum or a String compares the value with the labels. Without break, execution falls through into the next branch. That is a rarely needed trick and a very common defect. If two labels should do the same thing, the old style writes them one after another, empty, with a single break.

Modern Java has the switch expression: return switch (code) { case 200 -> "ok"; default -> "other"; };. The arrow does not fall through. The expression always has a result, and the compiler requires default or the full set of enum constants. For HTTP codes that is exactly what you want: each code is one branch, and a forgotten code does not stay silent.

Do not stuff a database call, a loop and five assignments into a case. A case should pick a value or call one method. A long case is a method hidden in the wrong place.

JDK 17 is enough for the training environment: switch expressions and record are already there. Java 21-only features, such as unnamed variables and new modes, are not needed in the tasks. Write code that builds on 17.

Practice

  1. Why break

    What happens in an old switch if a case has neither break nor an arrow?

    • The compiler always inserts break
    • Execution falls through further
    • switch returns null
    • the case becomes a loop
  2. The arrow

    Does an arrow switch with case 200 -> "ok" fall through into the next branch? Answer yes or no.

  3. Status class

    Write static String kind(int code). Return ok for 200, missing for 404 and other otherwise. Use an arrow switch.