// Basic switch expression
DayOfWeek day = DayOfWeek.MONDAY;
String dayType = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
// Switch expression with return value
int result = switch (operation) {
case "add" -> a + b;
case "subtract" -> a - b;
case "multiply" -> a * b;
case "divide" -> b != 0 ? a / b : 0;
default -> 0;
};
// Switch expression with block and yield
String message = switch (status) {
case "success" -> "Operation completed";
case "error" -> {
String errorMsg = "Error occurred";
yield errorMsg; // Must use yield in blocks
}
case "pending" -> "Operation in progress";
default -> "Unknown status";
};
// Switch expression with enum
enum Status { PENDING, IN_PROGRESS, COMPLETED }
int priority = switch (status) {
case PENDING -> 1;
case IN_PROGRESS -> 2;
case COMPLETED -> 3;
};
// Switch expression with null handling (Java 17+)
String result2 = switch (value) {
case null -> "Null value";
case "" -> "Empty";
case String s -> "String: " + s;
};
// Switch expression with pattern matching (Java 17+)
String description = switch (obj) {
case String s -> "String: " + s;
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
case null -> "Null";
default -> "Unknown type";
};
// Switch expression for month days
int days = switch (month) {
case JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER -> 31;
case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
case FEBRUARY -> isLeapYear ? 29 : 28;
};