Decision-making is in almost every method, and modern switch removes a whole class of fall-through bugs.
An if statement runs a block when a boolean condition is true, with optional else if and else branches. Always use braces, even for one line — it prevents bugs when someone adds a second statement later.
When you branch on one value against several constants, use switch. Modern Java (14+) has the arrow form, which does not fall through and can be used as an expression that yields a value:
String type = switch (day) {
case SATURDAY, SUNDAY -> "weekend";
default -> "weekday";
};- Several labels can share one case, separated by commas.
- A switch expression must be exhaustive: every possible input needs a case, usually via
default. For enums the compiler accepts listing every constant instead. - If a case needs several statements, use a block and
yieldthe result:case 3 -> { log(); yield "three"; }.
You can switch on int, char, String, enums and (since Java 21) any type with pattern-matching cases, which you'll meet later.
The old colon form case 1: still works but falls through into the next case unless you write break. Forgetting break is a classic bug, so prefer arrows in new code.
For simple two-way choices that produce a value, the ternary cond ? a : b is often clearest. For complex conditions, extract them into a well-named boolean variable or method so the if reads like a sentence.
Example
public class Grades {
static String letter(int score) {
if (score >= 90) {
return "A";
} else if (score >= 75) {
return "B";
} else {
return "C";
}
}
public static void main(String[] args) {
String cmd = "stop";
int code = switch (cmd) {
case "start", "run" -> 1;
case "stop" -> {
System.out.println("stopping...");
yield 0;
}
default -> -1;
};
System.out.println(letter(82) + " " + code); // B 0
}
}Remember
- Arrow-form
switchnever falls through and can return a value - Switch expressions must be exhaustive — add
default(or cover every enum constant) - Use
yieldto return a value from a multi-statement case block
Watch out for
- Using old
case X:labels and forgettingbreak, so execution falls into the next case.