Core Java

Java yield switch

In Java 14, the yield keyword is introduced to enhance switch expressions. It allows a value to be returned from a switch expression. Instead of just executing code blocks, yield produces a result that becomes the value of the switch expression. This simplifies code and enhances readability, making Java programming more efficient and expressive. Let us understand and explore the Java yield switch.

1. Introduction

Introduced in Java 14, the yield keyword revolutionizes the functionality of switch expressions. Traditionally, switch statements could not produce values. With yield, each case block can now return a specific value. This results in cleaner and more expressive code, enhancing readability and maintainability.

1.1 Benefits

  • Readability: yield establishes a direct connection between case labels and returned values, enhancing code clarity.
  • Conciseness: It simplifies syntax, eliminating the need for temporary variables and reducing code length.
  • Predictable Flow: Each case block’s value is explicitly defined, ensuring a predictable flow of data.

1.2 Use Cases

  • Data Transformation: Utilize yield for different data transformation scenarios where distinct cases require specific transformed results based on input conditions.
  • State Machines: Implement state machines efficiently; each state can yield a particular value, making the code expressive and self-explanatory.
  • Parser Implementations: Streamline parsing logic by using yield to return parsed values based on different parsing rules.
  • Configuration Handling: Handle various configurations effortlessly; yield can return specific configuration values based on provided conditions, enhancing reconfigurability.

2. Working Example

Here are a few examples demonstrating the use of the yield keyword in Java 14.

2.1 Basic usage

In the given Java code snippet, an enumeration called Season is declared, representing four seasons: SPRING, SUMMER, AUTUMN, and WINTER. The code utilizes a switch expression, where the current season (in this case, Season.SUMMER) is evaluated. Based on the current season, the daysInSeason variable is calculated using the yield keyword (represented as -> in the code). If the current season matches SUMMER, the switch yields a value of 60, indicating that there are 60 days in summer. This value is then displayed as output using System.out.println().

package com.jcg.example;

public class YieldExample {
    enum Season { SPRING, SUMMER, AUTUMN, WINTER }

    public static void main(String[] args) {
        Season currentSeason = Season.SUMMER;

        int daysInSeason = switch (currentSeason) {
            case SPRING, AUTUMN -> 30;
            case SUMMER -> 60;
            case WINTER -> 90;
            default -> throw new IllegalArgumentException("Unknown season: " + currentSeason);

        System.out.println("Days in the current season: " + daysInSeason);

Since currentSeason is set to Season.SUMMER, the code will match the SUMMER case and assign daysInSeason the value of 60. Therefore, the output will be –

Ide Output

Days in the current season: 60

2.2 Enhanced Switch Expression with Yield

The provided Java class demonstrates the usage of an enhanced switch expression to determine the type of a given day.

package com.jcg.example;

public class EnhancedSwitchExample {

    public static void main(String[] args) {
        Day currentDay = Day.WEDNESDAY;

        String dayType = switch (currentDay) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
            case SATURDAY, SUNDAY -> "Weekend";

        System.out.println("The current day is a " + dayType);

The Day enum represents the days of the week. In this example, the currentDay variable is set to Day.WEDNESDAY. The enhanced switch expression evaluates currentDay, and since it matches a weekday (WEDNESDAY), the assigned dayType is “Weekday”. The program prints –

Ide Output

The current day is a Weekday

3. Exhaustiveness

In Java 14, the introduction of the yield keyword in switch expressions enhances their exhaustiveness. Exhaustiveness in the context of switch expressions means that all possible cases are accounted for, leaving no room for unhandled scenarios. The yield keyword ensures exhaustiveness by allowing each case to provide a specific value.


public String getDayType(Day currentDay) {
    return switch (currentDay) {
        case SATURDAY, SUNDAY -> "Weekend";

In this example, the Day enum represents the days of the week. The getDayType method takes a Day enum as input and uses a switch expression with the yield keyword to determine if the input day is a weekday or a weekend day. By covering all possible values of the Day enum and providing corresponding results, the switch expression ensures exhaustiveness. If a new day is added to the Day enum in the future, the compiler will enforce updating the switch expression to handle this new case, thereby maintaining exhaustiveness and reducing the risk of unintended bugs related to missing cases.

4. Conclusion

Java 14’s introduction of the yield keyword represents a significant leap forward in the language’s evolution. By enabling switch expressions to produce specific values, yield brings a newfound simplicity and elegance to Java programming. It eliminates boilerplate code, enhancing readability and maintainability while reducing the chances of human error.

The yield keyword not only streamlines the syntax but also promotes a more expressive and intuitive coding style. It allows developers to focus on the logic and intent of their code, making it easier to understand and modify. Furthermore, its ability to enhance exhaustiveness ensures that all cases are considered, making Java applications more robust and reliable.


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button