Lesson 12 / 38
Switch Expressions, Ternary & Labels
Master modern switch expressions with yield, chain ternary operators readably, and use labelled break/continue to control nested loops precisely.
switch with yield
A switch expression arm can be a full block instead of a single value — use yield to produce the result from inside it. Every path must yield a value, and the compiler checks all enum/sealed cases are covered.
int stars = switch (rating) {
case 1, 2 -> 1;
case 3 -> 3;
default -> {
int bonus = rating > 5 ? 1 : 0;
yield rating + bonus;
}
};Ternary — use sparingly
cond ? a : b is great for one simple choice assigned to a variable. Nesting ternaries (a ? b : c ? d : e) reads badly — prefer an if/else chain or a switch expression once it gets that complex.
Labelled break/continue
A label before a loop lets break label; or continue label; target that specific (possibly outer) loop from deep inside nested loops — the only clean way to bail out of two loops at once.
search:
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == target) {
System.out.println(i + "," + j);
break search; // exits BOTH loops
}
}
}