Mastering Java Switch Expressions: From Classic Switch to Yield and Pattern Matching

This article walks through modernizing a Java switch statement—from the traditional switch with breaks to the concise switch expression introduced in JDK 12, covering enum handling, the new arrow syntax, the yield keyword, compiler warnings, and practical code examples.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Java Switch Expressions: From Classic Switch to Yield and Pattern Matching

Introduction

During a code review of a colleague's implementation, the author noticed an outdated switch statement and decided to explore how to modernize it.

Classic Switch Example

private static String createPlayer(PlayerTypes playerType) {
    switch (playerType) {
        case TENNIS:
            return "网球运动员费德勒";
        case FOOTBALL:
            return "足球运动员C罗";
        case BASKETBALL:
            return "篮球运动员詹姆斯";
        case UNKNOWN:
            throw new IllegalArgumentException("未知");
        default:
            throw new IllegalArgumentException("运动员类型: " + playerType);
    }
}

The original code works but requires a default clause to satisfy the compiler.

Adding a Variable and Breaks

private static String createPlayer(PlayerTypes playerType) {
    String player = null;
    switch (playerType) {
        case TENNIS:
            player = "网球运动员费德勒";
            break;
        case FOOTBALL:
            player = "足球运动员C罗";
            break;
        case BASKETBALL:
            player = "篮球运动员詹姆斯";
            break;
        case UNKNOWN:
            throw new IllegalArgumentException("未知");
        default:
            throw new IllegalArgumentException("运动员类型: " + playerType);
    }
    return player;
}

By introducing a player variable and break statements, the default clause becomes optional.

Switch Expression (JDK 12+)

private static String createPlayer(PlayerTypes playerType) {
    return switch (playerType) {
        case TENNIS -> "网球运动员费德勒";
        case FOOTBALL -> "足球运动员C罗";
        case BASKETBALL -> "篮球运动员詹姆斯";
        case UNKNOWN -> throw new IllegalArgumentException("未知");
    };
}

The new arrow syntax eliminates the need for break and makes the switch a true expression that returns a value.

Handling New Enum Values

public enum PlayerTypes {
    TENNIS,
    FOOTBALL,
    BASKETBALL,
    PINGPANG,
    UNKNOWN
}

When a new constant PINGPANG is added, the compiler issues a warning that the switch does not cover all enum values. Adding the missing case resolves the warning.

private static String createPlayer(PlayerTypes playerType) {
    return switch (playerType) {
        case TENNIS -> "网球运动员费德勒";
        case FOOTBALL -> "足球运动员C罗";
        case BASKETBALL -> "篮球运动员詹姆斯";
        case PINGPANG -> "乒乓球运动员马龙";
        case UNKNOWN -> throw new IllegalArgumentException("未知");
    };
}

Multiple Labels in One Case

private static String createPlayer(PlayerTypes playerType) {
    return switch (playerType) {
        case BASKETBALL, PINGPANG -> "牛逼运动员沉默王二";
        // other cases omitted for brevity
    };
}

Multiple enum constants can be combined using commas.

Using yield in Switch Expressions

private static String createPlayer(PlayerTypes playerType) {
    return switch (playerType) {
        case TENNIS -> {
            System.out.println("网球");
            yield "网球运动员费德勒";
        }
        case FOOTBALL -> {
            System.out.println("足球");
            yield "足球运动员C罗";
        }
        // other cases omitted
        case UNKNOWN -> throw new IllegalArgumentException("未知");
    };
}

The yield statement produces the value for the enclosing switch expression, similar to return but usable inside a block.

Bytecode Insight

private static String createPlayer(NewSwitchDemo3.PlayerTypes playerType) {
    String var10000;
    switch (playerType) {
        case TENNIS:
            System.out.println("网球");
            var10000 = "网球运动员费德勒";
            break;
        // other cases omitted
        case UNKNOWN:
            throw new IllegalArgumentException("未知");
        default:
            throw new IncompatibleClassChangeError();
    }
    return var10000;
}

In the compiled bytecode, yield is translated into a traditional break with a temporary variable.

Conclusion

While the new switch expression syntax looks fashionable, developers should weigh readability, compatibility with older JDK versions, and team familiarity before adopting it; sometimes the classic switch remains the most pragmatic choice.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaYieldswitch expressionCode TutorialJDK13
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.