Java yield Keyword

The yield keyword in Java is used in the context of switch expressions, introduced in Java 12 as a preview feature and made a standard feature in Java 14. The yield keyword allows returning a value from a case block within a switch expression.

Table of Contents

  1. Introduction
  2. yield in Switch Expressions
    • Syntax
    • Examples
  3. Real-World Use Case
  4. Conclusion

Introduction

The yield keyword is used within a switch expression to return a value from a particular case. This enhances the switch statement by allowing it to be used as an expression that can return a value, making the code more concise and expressive.

yield in Switch Expressions

Syntax

The syntax for using the yield keyword in a switch expression is as follows:

var result = switch (expression) { case value1 -> value1Result; case value2 -> { // code block yield value2Result; } default -> defaultValue; }; 

Example

To demonstrate the usage of the yield keyword in a switch expression, we will calculate a value based on the input using a switch expression.

public class YieldSwitchExample { public static void main(String[] args) { int day = 3; String dayType = switch (day) { case 1, 2, 3, 4, 5 -> "Weekday"; case 6, 7 -> "Weekend"; default -> { System.out.println("Invalid day"); yield "Unknown"; } }; System.out.println("Day type: " + dayType); } } 

Output:

Day type: Weekday 

Real-World Use Case

Mapping Enums to Descriptions

In real-world applications, the yield keyword can be used to map enum values to their corresponding descriptions using a switch expression.

Example

public class YieldRealWorldExample { enum TrafficLight { RED, YELLOW, GREEN } public static void main(String[] args) { TrafficLight signal = TrafficLight.RED; String action = switch (signal) { case RED -> "Stop"; case YELLOW -> { System.out.println("Caution"); yield "Slow Down"; } case GREEN -> "Go"; }; System.out.println("Action: " + action); } } 

Output:

Action: Stop 

Conclusion

The yield keyword in Java enhances switch expressions by allowing them to return values from individual case blocks. This makes the code more concise and expressive, providing a more flexible and powerful alternative to traditional switch statements. By understanding and using the yield keyword, you can write more modern and efficient Java code.

Leave a Comment

Scroll to Top