Arrow-Style switch
Use the modern switch arrow syntax.
The Old switch Problem
The classic Java switch statement used colon labels and required break after every case. Forgetting break caused fall-through bugs where execution slid into the next case.
Modern Java (14+) introduces the arrow syntax that fixes this entirely.
Arrow Syntax Basics
With arrow-style switch, each label uses -> instead of :. There is no fall-through and no break needed. Each branch runs only its own code.
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1 -> System.out.println("Monday");
case 3 -> System.out.println("Wednesday");
default -> System.out.println("Other day");
}
}
}All lessons in this course
- Arrow-Style switch
- switch as an Expression
- The yield Keyword
- Multi-Label Cases