Home › Java Tutorial › Java switch
Java switch
Choose between many values.
The classic switch needs break after each case, or execution falls through to the next one. Since Java 14 a switch expression with -> returns a value and needs no break.
Example code
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("Other");
}
String name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 3 -> "Wed";
default -> "Other";
};
System.out.println(name);
}
}