• 🧠 Switch Expressions in Java

    — Illustrated with French Poets Across Centuries

    Like all expressions, switch expressions in Java evaluate to a single value. This value can be used directly in assignments or output statements.

    Starting with Java 14, we can use the more concise and safer case L -> labels. These eliminate the need for break statements and make the code easier to read and less error-prone. When needed, you can also use yield in a block to return a value.

    📖 For the design motivation behind this feature, see JEP 361.

    🎨 Example Scenario — Poets and Their Centuries

    Let’s say you’re working with an enum of famous French poets, and you want to determine the century in which each poet lived and wrote.

    🐢 Classic Switch Statement

    Here's how this might look using a traditional switch statement to determine a poet’s century:

    👎 Downsides of the classic approach:

    🟣 You have to declare and mutate a variable (century).

    🟣 You must remember to add break statements — forgetting one could cause fall-through bugs.

    ⚡ Modern Switch Expression

    With switch expressions, this becomes much cleaner and less error-prone:

    🧾 Why It’s Better

    🟣 Each case is followed by ->, which directly points to a returned value.

    🟣 No need for break.

    🟣 The whole construct is an expression, which means you can assign or return it inline.

    🟣 It's safe by design — no fall-through means fewer bugs.

    📌 Summary

    ✅ case L -> is called a switch labeled rule.

    🟣 Avoids the need for break.

    🟣 Prevents accidental fall-through.

    🟣 Can be used in both expressions and statements.

    🟣 Makes your code cleaner, safer, and more expressive.