← Back to list

Modern Switch Expressions in Java

The modern switch expression, introduced in Java 12 as a preview feature and made stable in Java 14, simplifies the traditional switch…

Santiago · 2024-12-28 23:58 · 0 claps · 1.5 min read
#switch #java-14 #java17 #java12 #clean-code
Open on Medium ↗
Wiki topics: 🌐 · Web Development 📰 · Journalism & News

Modern Switch Expressions in Java

The modern switch expression, introduced in Java 12 as a preview feature and made stable in Java 14, simplifies the traditional switch statement. The modern switch eliminates the need for explicit break statements and avoids accidental fallthrough, which was a common source of bugs in traditional switch statements.

Arrow Syntax (->)

  • Replaces the traditional case blocks with a cleaner syntax.
  • Avoids fallthrough by default.

Simplified Syntax

  • No need for break statements.
  • Multiple values for a single case can be handled with commas.

Modern Switch syntax

This example categorizes phone numbers based on their prefix. It demonstrates the modern switch syntax and its ability to handle multiple cases cleanly.

public class PhoneNumberCategorizer {
    public static void main(String[] args) {
        final String phoneNumber = "1234567890";

        // Extract the prefix (first three digits)
        final String prefix = phoneNumber.substring(0, 3);

        // Categorize the phone number
        final String category = switch (prefix) {
            case "123", "124", "125" -> "Business Line"; // Handles multiple prefixes
            case "234", "235" -> "Personal Line";
            case "345", "346", "347" -> "Support Line";
            default -> "Unknown Line"; // Default case handles unmatched prefixes
        };
        // Print the result
        System.out.println("Phone Number: " + phoneNumber);
        System.out.println("Category: " + category);
    }
}

Phone Number: 1234567890 Category: Business Line

Traditional Switch Syntax (Old Style)

public class PhoneNumberCategorizerOldStyle {
    public static void main(String[] args) {
        final String phoneNumber = "1234567890";

        // Extract the prefix (first three digits)
        final String prefix = phoneNumber.substring(0, 3);

        // Categorize the phone number using traditional switch
        String category;
        switch (prefix) {
            case "123":
            case "124":
            case "125":
                category = "Business Line";
                break;
            case "234":
            case "235":
                category = "Personal Line";
                break;
            case "345":
            case "346":
            case "347":
                category = "Support Line";
                break;
            default:
                category = "Unknown Line";
        }

        // Print the result
        System.out.println("Phone Number: " + phoneNumber);
        System.out.println("Category: " + category);
    }
}

Drawbacks of Traditional Switch

Verbose Code

Repetition of case statements for handling multiple values (e.g., case "123":, case "124":, etc.) increases code verbosity.

Fallthrough Risk

Without break statements, execution unintentionally "falls through" to the next case, potentially causing bugs.

No Return Values

The traditional switch cannot directly return a value; you need to assign the result manually to a variable.

Readability

The verbosity and manual break handling reduce code readability, especially for complex switch logic.

Advantages of Modern Switch

Conciseness

Cleaner and shorter code, reducing boilerplate.

Safety

Avoids fallthrough errors.


메타데이터
post_id
2d0c4d02e0dc
slug
modern-switch-expressions-in-java-2d0c4d02e0dc
url
https://medium.com/@barbieri.santiago/modern-switch-expressions-in-java-2d0c4d02e0dc
canonical_url
https://medium.com/@barbieri.santiago/modern-switch-expressions-in-java-2d0c4d02e0dc
author_url
https://medium.com/@barbieri.santiago
status
ok
fetched_at
2026-07-19 21:53:32