0Pricing
Java Academy · Lesson

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

  1. Arrow-Style switch
  2. switch as an Expression
  3. The yield Keyword
  4. Multi-Label Cases
← Back to Java Academy