When one value is compared against several constants, switch reads better than an else if chain. The modern arrow form has no fall-through: case "sat", "sun" -> "weekend"; lists the matches, default -> catches the rest, and the whole thing can be an expression that produces a value: String kind = switch (day) { ... };. It works on numbers, strings, characters, and enums.
A case with a block uses yield to produce the value: case 2 -> { int d = leap ? 29 : 28; yield d; }. You will also meet the old form, case 1: with break; after each case, in existing code; it falls through to the next case when the break is missing, which was a source of bugs for decades.
String kind = switch (day) {
case "sat", "sun" -> "weekend";
default -> "weekday";
};Your task
Write static String dayType(String day) returning "weekend" for "sat" and "sun", "weekday" for the other five short names, and "unknown" for anything else. Then write static int daysIn(int month) returning 31, 30, or 28 for month numbers 1 to 12 (February is 28 here), and 0 for any other number.
Hint 1
return switch (day) { case "sat", "sun" -> "weekend"; case "mon", "tue", "wed", "thu", "fri" -> "weekday"; default -> "unknown"; };
Hint 2
case 1, 3, 5, 7, 8, 10, 12 -> 31; case 4, 6, 9, 11 -> 30; case 2 -> 28; default -> 0;
Show the solution
public class Main {
static String dayType(String day) {
return switch (day) {
case "sat", "sun" -> "weekend";
case "mon", "tue", "wed", "thu", "fri" -> "weekday";
default -> "unknown";
};
}
static int daysIn(int month) {
return switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> 0;
};
}
public static void main(String[] args) {
System.out.println(dayType("sat") + " " + daysIn(2));
}
}