2 · Control Flow & Methods · lesson 8 of 41

switch & Pattern Switch

Classic switch statements and modern arrow-style expressions.

Java
// Modern switch expression (Java 14+)
String day = switch (n) {
    case 1, 7 -> "weekend";
    case 2, 3, 4, 5, 6 -> "weekday";
    default -> "unknown";
};

// Pattern switch (Java 21+)
String describe = switch (obj) {
    case Integer i when i > 0 -> "positive int " + i;
    case String  s            -> "string of length " + s.length();
    case null                 -> "nothing";
    default                   -> "something else";
};
Key takeaways
  • ✓Arrow switch expressions return values and have no fall-through.
  • ✓Pattern switch dispatches on the runtime type and can bind variables.