DEV Community

levi
levi

Posted on

Day 6- Switch Smarter in Java 21

Day 6: Learnt About Modern switch in Java 21

Goodbye Break, Hello ->

Modern switch in Java 21 allows using arrow syntax (->), so you can skip the break keyword and avoid accidental fall-throughs.

Without arrow syntax, you can use the yield keyword to return a value from a switch expression.

  • To group multiple case values, use a comma-separated list: case 1,2 ->
  • When using a sealed hierarchy, the compiler checks for exhaustiveness at compile time:
sealed interface Shape permits Circle, Square {}
final class Circle implements Shape {}
final class Square implements Shape {}

String result = switch (shape) {
    case Circle c -> "Circle!";
    case Square s -> "Square!";
};
Enter fullscreen mode Exit fullscreen mode
  • it also supports null case unlike classic java.
    case null->"no"

  • It supports pattern matching and guards (when), allowing type checks and additional conditions directly in switch:

Object obj = 10;

String result = switch (obj) {
    case Integer i when i > 5 -> "Large number";
    case Integer i -> "Small number";
    default -> "Other";
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)