Sub topic 9
Compute a Value with an Exhaustive switch Expression and yield
Use switch when you need a value
A switch statement chooses an action to run. A switch expression chooses a value to use. An expression is a piece of code that produces a value, like 20 minus 5. You can save the result of a switch expression in a variable, just as you can save the result of that subtraction.
Think of a ticket desk. The ticket type tells you which price to charge. You could print the price inside each case, but then the decision and the printing would be mixed together. Instead, let the switch compute the price. After the switch, you can print it, add it to a total, or use it in another calculation.
Work through a ticket price
This example uses Java 14 or later. Save it in a file named TicketPrice.java. The selector is the value the switch checks. Here, it is ticketType, a String, which is Java’s type for text.
public class TicketPrice {
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: " + ticketType
);
};
System.out.println(price);
}
}Run these commands from the folder where you saved the file. The first command compiles the program, which means it turns your source code into a form Java can run. The second runs it.
javac TicketPrice.java
java TicketPriceThe program prints 15. Follow the value from the matching case to the print line:
- Java reads ticketType and matches the text child.
- The child rule sets discount to 5. Then it subtracts 5 from the base price of 20.
- The yield keyword makes 15 the result of the whole switch expression. Java stores that result in price.
- The print line reads price and displays 15. The adult rule does not run.
Know when to write yield
The adult rule has just one expression after its arrow: basePrice. Java uses that expression’s value directly. No yield is needed.
The child rule needs an extra step: it creates a discount variable before doing the subtraction. It puts those steps in a block, which is a group of code inside braces. Java does not treat the last line of a block as its result by itself. Use yield to say which value the block gives to the switch.
Yield ends the switch expression, not the whole method. A method is a named group of instructions, such as main in this example. That is why the print line in main still runs after yield. Also notice the semicolon after the last brace of the switch. The brace closes the switch, and the semicolon ends the instruction that creates price.
Cover every choice, including bad input
A switch expression must be exhaustive. That means Java can see that there is a rule for every choice it needs to cover. When the selector is a String, listing child and adult is not enough: someone might pass in senior, a misspelling, or even empty text. Java checks that the switch has enough rules when you compile it. Removing default from this example causes a compile error, even if you leave ticketType set to child.
The default rule catches text that does not match a listed case. Here, it uses throw to signal an exception, which means the program could not complete the work as planned. The exception name IllegalArgumentException tells you that the code got a value it does not accept. Since this program does not handle the exception, it stops without printing a price.
That error path is allowed. A rule that finishes normally must give the switch a value. A rule that throws does not finish normally, so there is no price to store. This lets you reject an unknown ticket type instead of silently charging the adult price.
Check all three paths
Change the starting value of ticketType to each value below. Compile and run the program again after each change. Before you run it, predict whether the print line will run.
| Value of ticketType | What the matching rule does | What you see |
|---|---|---|
| child | Calculates a discount and yields 15 | A price of 15 |
| adult | Uses the base price directly | A price of 20 |
| senior | Throws an exception in default | An error message and no price |
Try one more change: leave the child rule’s block in place but delete its yield line. Even though the block still sets discount, the program no longer compiles. Setting a variable inside a case does not give the switch a result. Restore the yield line before moving on.
Exercise
If the base price is 30 and the ticket type is child, what is printed? Which line gives the switch its result?
Show answer
The program prints 25. The line yield basePrice - discount; gives the switch the result of 30 minus 5.
Exercise
Add a student case that charges 2 less than the base price. Can the rule give that price without using yield?
Show answer
Yes. Add case "student" -> basePrice - 2; before default. The subtraction is a single expression, so Java uses its value directly. With a base price of 20 and ticketType set to student, the program prints 18.