Java Switch
switch picks one of many branches by value. Modern Java has an arrow form that does not need break.
ExampleJava
public class Main {
public static void main(String[] args) {
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Another day";
};
System.out.println(name);
// Classic form needs break
switch (day) {
case 3:
System.out.println("Midweek");
break;
default:
System.out.println("Other");
}
}
}Output
Wednesday Midweek
Quick check
In the classic switch, what stops execution falling into the next case?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.