---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 16 Edition"
java_version: 16
chapter: "Chapter 14. Blocks, Statements, and Patterns"
section: "14.21"
heading: "14.21. The yield Statement"
parent: "Chapter 14. Blocks, Statements, and Patterns"
source: https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-14.21
id: "14.21"
url: https://jvm.obfuscated.software/jls/se16/14.21.html
raw: https://jvm.obfuscated.software/jls/se16/14.21.md
---

# 14.21. The `yield` Statement

A `yield` statement transfers control by causing an enclosing `switch` expression ([§15.28](15.28.md)) to produce a specified value.

```
YieldStatement:
  yield Expression ;
```

A `yield` statement attempts to transfer control to the innermost enclosing `switch` expression; this enclosing expression, which is called the *yield target*, then immediately completes normally and the value of the *Expression* becomes the value of the `switch` expression.

It is a compile-time error if a `yield` statement has no yield target.

It is a compile-time error if the yield target contains any method, constructor, instance initializer, static initializer, or lambda expression that encloses the `yield` statement. That is, there are no non-local jumps.

It is a compile-time error if the *Expression* of a `yield` statement is void ([§15.1](15.1.md)).

Execution of a `yield` statement first evaluates the *Expression*. If the evaluation of the *Expression* completes abruptly for some reason, then the `yield` statement completes abruptly for that reason. If evaluation of the *Expression* completes normally, producing a value `V`, then the `yield` statement completes abruptly, the reason being a yield with value `V`.

It can be seen, then, that a `yield` statement always completes abruptly.

**Example 14.21-1. The `yield` Statement**

In the following example, a `yield` statement is used to produce a value for the enclosing `switch` expressions.

```
 class Test {
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
	SATURDAY, SUNDAY
    }

    public int calculate(Day d) {
        return switch (d) {
	    case SATURDAY, SUNDAY -> d.ordinal();
            default -> {
                int len = d.toString().length();
                yield len*len;
            }
        };
    }
}
```
