TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
yield statement in Java is a context-sensitive keyword introduced in Java 14 (JEP 361) used to explicitly return a value from a block within a switch expression. It transfers control and the evaluated result of its target expression back to the enclosing switch expression, acting analogously to a return statement but scoped strictly to the switch block rather than the enclosing method.
Syntax
Mechanics and Execution Rules
- Switch Expressions Only:
yieldcan only be utilized within aswitchexpression (aswitchconstruct that evaluates to a single value). It results in a compilation error if used within a traditionalswitchstatement. - Block Scoping: It is mandatory when a branch of a
switchexpression requires a full code block{ ... }to execute multiple statements before producing a value. - Type Compatibility: The
<expression>provided to theyieldstatement must be assignment-compatible with the declared or inferred type of the enclosingswitchexpression. - Exhaustiveness: Because
yieldis tied toswitchexpressions, the compiler enforces exhaustiveness. Every possible execution path within theswitchmust eitheryielda value or throw an exception. - Restricted Identifier: To maintain backward compatibility,
yieldis a restricted identifier, not a globally reserved keyword. It acts as a keyword only within the context of aswitchblock. It remains valid to useyieldas a variable or method name elsewhere in the codebase.
Syntax Visualization
Arrow Syntax (->) with Blocks
When using the arrow syntax, single expressions implicitly yield their value. The yield keyword is only required when opening a block.
:) in Expressions
If a switch expression utilizes traditional colon syntax (fall-through semantics), yield replaces the break statement to simultaneously prevent fall-through and provide the branch’s evaluated value.
yield vs. return
It is critical to distinguish yield from return regarding control flow:
yieldterminates the execution of theswitchexpression and provides a value to the variable capturing the expression’s result.returnterminates the execution of the enclosing method or lambda, passing control back to the caller. Usingreturninside aswitchexpression is a compilation error.
Master Java with Deep Grasping Methodology!Learn More





