public class SwitchExpressionUtils {
// Basic switch expression
public static String getDayType(DayOfWeek day) {
return switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
}
// Switch expression with multiple statements
public static int calculate(int value, String operation) {
return switch (operation) {
case "double" -> value * 2;
case "square" -> value * value;
case "triple" -> value * 3;
default -> value;
};
}
// Switch expression with block
public static String process(int value) {
return switch (value) {
case 0 -> "Zero";
case 1, 2, 3 -> "Small";
case 4, 5, 6 -> {
String result = "Medium: " + value;
yield result; // Use yield for blocks
}
default -> "Large";
};
}
// Switch expression with enum
public static int getPriority(Status status) {
return switch (status) {
case PENDING -> 1;
case IN_PROGRESS -> 2;
case COMPLETED -> 3;
case CANCELLED -> 0;
};
}
// Switch expression with null handling
public static String handleValue(String value) {
return switch (value) {
case null -> "Null value";
case "" -> "Empty string";
case String s when s.length() > 10 -> "Long string";
default -> "Normal string: " + value;
};
}
// Switch expression with pattern matching (Java 17+)
public static String describe(Object obj) {
return switch (obj) {
case String s -> "String: " + s;
case Integer i -> "Integer: " + i;
case Double d -> "Double: " + d;
case null -> "Null";
default -> "Unknown";
};
}
}