← Java from Scratch
Lesson 15 of 88 · 10 XP
switch
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
The classic switch (as in C) needs break, otherwise execution "falls through" into the next case:
switch (day) {
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
}
Since Java 14 there's the arrow switch: no fall-through, and it can return a value:
String name = switch (day) {
case 1 -> "Monday";
case 6, 7 -> "Weekend";
default -> "Weekday";
};
switch works with int, char, String and enum.
Task. Read a command string and a number: add 5, sub 3, mul 4, div 2 — apply it to the starting
value 10 (integer division); for any other command print unknown. Use a switch on the string.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.