What it is and why to use it
A switch expression evaluates to a value. This is useful when translating a status or menu choice into one result. It became standard in Java 14. Arrow rules do not fall through into the next rule, which avoids the accidental missing-break behaviour associated with colon-style switch statements.
How it works
A simple arrow rule can supply an expression directly. A rule that needs several statements uses a block and yield to supply the switch result. Every possible selector value must be covered, using default where needed. The semicolon after the closing brace ends the variable declaration.
Common mistakes and limitations
Do not use break with a value in this syntax, or confuse yield with return. This Java 17 String switch does not accept null: validate nullable inputs before switching.
Try it and keep learning
Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.
Syntax
int value = switch (choice) { case "small" -> 1; default -> 2; };Examples
switch Expressions and yield
Complete Main.java example — Java 17 or later, without preview features.
public class Main {
public static void main(String[] args) {
String size = "medium";
int portions = switch (size) {
case "small" -> 1;
case "medium" -> {
int base = 2;
yield base + 1;
}
default -> 4;
};
System.out.println(portions);
}
}- size selects the medium rule.
- The block creates base with value 2; yield base + 1 supplies 3 as the switch result.
- portions receives that value and println displays it. yield exits the switch expression’s rule; it does not return from main.
- Expected output: 3
Best practices
- Use expressions for value selection and statements for other control flow.
- Make unexpected inputs explicit rather than silently assigning an inappropriate default.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification