Sub topic 3
Use Arrow-Style Cases That Do Not Fall Through
Run Only the Matching Case
A switch statement picks an action based on one value. That value is called the selector. Each case names a value to match. The default rule runs if no case matches.
In Java 14 and later, you can write cases with arrows. Java runs only the matching rule, then leaves the switch. There is no fall-through, which means Java does not continue into the next case. You do not need break to stop it.
Save this as Commands.java and run it with java Commands.java.
public class Commands {
public static void main(String[] args) {
String command = "help";
switch (command) {
case "help" -> System.out.println("Show available commands");
case "quit" -> System.out.println("Goodbye");
default -> System.out.println("Unknown command");
}
}
}The program prints only “Show available commands.” Change the command to “save” and run it again. This time, neither case matches, so the program prints “Unknown command.”
Choose Between if and switch
- Use if for ranges, such as scores of 70 or higher. Use it for other predicates too. A predicate is a test that gives true or false, such as checking whether a store is open and an item is in stock.
- Use switch when you compare one selector with a list of exact values, such as “help” and “quit.” These separate choices are called discrete cases.
Compute a Value with a switch Expression
An expression is code that produces a value. Use a switch expression when you want a result, such as a price, rather than just an action. A switch expression must be exhaustive: it must cover all choices. Here, default covers other ticket names and throws an exception, which reports an error instead of giving a price.
Save this as Tickets.java and run it with java Tickets.java.
public class Tickets {
public static void main(String[] args) {
int basePrice = 20;
String ticketType = "child";
int price = switch (ticketType) {
case "child" -> {
int discount = 5;
yield basePrice - discount;
}
case "adult" -> basePrice;
default -> throw new IllegalArgumentException("Unknown ticket type");
};
System.out.println(price);
}
}A block is code inside braces. In the child block, yield gives the switch its result, 15. The adult case gives its value right after the arrow. The semicolon after the closing brace ends the assignment to price.
Exercise
What will Tickets print if you change ticketType to "adult"? Does that case need yield?
Show answer
It prints 20. The adult case gives its value directly after the arrow, so it does not need yield.