Java Switch Expressions

Modern switch syntax that returns values and supports multiple patterns (Java 14+)

java (14+) 2025-11-03 switch expressions java14 control-flow

Description

Switch expressions were introduced in Java 14 as a preview feature and became standard in Java 14. They provide a more concise syntax for switch statements and can return values, making code more readable and less error-prone.

Key Features

  • Expression syntax: Switch can return values
  • Arrow syntax: case label -> value instead of case label: break;
  • Multiple labels: case A, B -> value
  • No fall-through: Each case is independent
  • Pattern matching: Use with pattern matching (Java 17+)
  • Null handling: Explicit null case handling

Benefits

  • Less boilerplate: No break statements needed
  • More readable: Clear expression of intent
  • Safer: No accidental fall-through
  • Exhaustive: Compiler can check all cases covered
  • Functional style: More expression-oriented

Comparison with Switch Statements

  • Statements: Execute code blocks, no return value
  • Expressions: Return values, can be assigned
  • Arrow syntax: Available in both, but more common in expressions

Code

RAW
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";        };    }}
RAW
// Basic switch expressionDayOfWeek day = DayOfWeek.MONDAY;String dayType = switch (day) {    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";    case SATURDAY, SUNDAY -> "Weekend";};// Switch expression with return valueint 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 yieldString 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 enumenum 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 daysint days = switch (month) {    case JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER -> 31;    case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;    case FEBRUARY -> isLeapYear ? 29 : 28;};

Comments

No comments yet. Be the first to comment!