javabeginner

Switch Expressions — Modern Java

Use switch expressions with arrow syntax, pattern matching, guards, and yield for concise branching.

java
public class SwitchExpressions {

    // 1. Basic switch expression (arrow syntax)
    static String dayType(String day) {
        return switch (day.toUpperCase()) {
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
            case "SATURDAY", "SUNDAY" -> "Weekend";
            default -> throw new IllegalArgumentException("Unknown day: " + day);
        };
    }

    // 2. Switch with yield (multi-line cases)
    static double shippingCost(String tier, double weight) {
        return switch (tier) {
            case "standard" -> weight * 0.50;
            case "express" -> weight * 1.50;
            case "overnight" -> {
                double base = weight * 3.00;
                double surcharge = weight > 10 ? 15.0 : 5.0;
                yield base + surcharge;
            }
            default -> throw new IllegalArgumentException("Unknown tier");
        };
    }

    // 3. Pattern matching with sealed types (Java 21+)
    sealed interface Payment permits CreditCard, BankTransfer, Crypto {}
    record CreditCard(String number, double amount) implements Payment {}
    record BankTransfer(String iban, double amount) implements Payment {}
    record Crypto(String wallet, String coin, double amount) implements Payment {}

    static String processPayment(Payment payment) {
        return switch (payment) {
            case CreditCard cc when cc.amount() > 10000 ->
                "Large CC payment: requires verification";
            case CreditCard cc ->
                "Charging card ending " + cc.number().substring(cc.number().length() - 4);
            case BankTransfer bt ->
                "Wire transfer to " + bt.iban();
            case Crypto c when "BTC".equals(c.coin()) ->
                "Bitcoin payment to " + c.wallet();
            case Crypto c ->
                "Crypto payment: " + c.coin();
        };
    }

    // 4. Null handling in switch (Java 21+)
    static String format(Object obj) {
        return switch (obj) {
            case null -> "null";
            case Integer i -> "int: " + i;
            case String s when s.length() > 10 -> "long string";
            case String s -> "string: " + s;
            default -> obj.toString();
        };
    }

    public static void main(String[] args) {
        System.out.println(dayType("Monday"));     // Weekday
        System.out.println(shippingCost("overnight", 15)); // 60.0
        System.out.println(processPayment(new CreditCard("4111111111111234", 500)));
        System.out.println(format(null)); // null
    }
}

Use Cases

  • Concise branching logic replacing verbose if-else
  • Type-safe payment or status processing
  • Pattern matching with sealed hierarchies

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.