The yield Keyword
Produce values from switch blocks.
When One Line Is Not Enough
An arrow branch like case 1 -> 42; returns a value directly. But what if a branch needs several statements before producing its value? That is where yield comes in.
The yield Keyword
Inside a block branch { }, the yield keyword supplies the value that the switch expression produces. Think of it as return, but for a switch branch.
public class Main {
public static void main(String[] args) {
int n = 3;
int result = switch (n) {
case 3 -> {
int squared = n * n;
yield squared;
}
default -> 0;
};
System.out.println(result);
}
}All lessons in this course
- Arrow-Style switch
- switch as an Expression
- The yield Keyword
- Multi-Label Cases