Nearby lessons
99 of 125Java - Switch Expressions
- Switch expressions (first preview)
- String indent() and transform()
- Collectors.teeing
- Compact number formatting
Switch Expressions is a core concept of the Java language. This lesson explains Java 12 — The Switch Gets Modern, Old Switch vs New Switch Expression and Old Switch vs New Switch — Comparison with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Java 12 — The Switch Gets Modern
Java 12 (March 2019) is a small version but it started one of the most loved changes: making the old switch statement into a modern switch expression. (It was a preview here; it became final in Java 14.)
Old Switch vs New Switch Expression
The old switch is verbose and easy to break (forgetting break causes fall-through bugs). The new switch expression is short and safe:
Old Switch vs New Switch Expression
See the difference — the new style: no break, multiple values on one case (case 1, 3, 5, 7), and it returns a value directly into the variable. The arrow -> means if this case matches, produce this value.
Old Switch vs New Switch — Comparison
| Point | Old switch statement | New switch expression |
|---|---|---|
| break needed? | Yes (fall-through bugs) | No |
| Returns a value? | No (you assign inside cases) | Yes — the whole switch gives a value |
| Multiple values per case | Separate case lines | case 1, 3, 5 -> |
| Style | Colon : | Arrow -> (or yield for blocks) |
| Since | Java 1.0 | Final in Java 14 |
Switch Expressions — Now with yield
Java 13 added a second style to switch expressions: the yield keyword for the block style (for cases with more than one statement):
Switch Expressions — Now FINAL
Switch expressions, previewed in Java 12 and 13, became a standard, permanent feature in Java 14. No --enable-preview needed anymore.
- Java 12 introduced switch expressions as a preview — no break, arrows, returns a value.
- indent(n) adds/removes leading spaces on every line.
- transform() chains String operations in one line.
- Collectors.teeing() runs two collectors at once and merges results.
- CompactNumberFormat shows big numbers as 1.2K, 3.5M.
- Preview features are experiments that become final later.