Sub topic 9
Compute a Value with an Exhaustive switch Expression and yield
A switch statement can choose what your program does. A switch expression can choose a value for your program to use. An expression is a piece of code that produces a value. For example, 20 - 5 produces 15. A switch expression can also produce 15, but it can use a different calculation for each case.
This is useful when several cases feed into the same next step. In a ticket program, each case can work out a price. Then one line after the switch can print that price.
You’ll need Java 14 or later for the examples. To run an example, save it in a file with the name shown. Then enter the given java command in a terminal, a window where you type commands.
Use One Case to Set a Variable
Start with a café that sells tea for 2 dollars and coffee for 3 dollars. In this example, other drinks have a price of 0. We’ll look at when that kind of fallback is a good idea.
Save this program as DrinkPrice.java and run java DrinkPrice.java.
public class DrinkPrice {
public static void main(String[] args) {
String drink = "tea";
int price = switch (drink) {
case "tea" -> 2;
case "coffee" -> 3;
default -> 0;
};
System.out.println(price);
}
}The program prints 2. Here’s how Java gets that number:
- Java reads
drink. It is the selector, the value thatswitchuses to choose a case. - The selector is
"tea", so Java picks the rule labeledcase "tea". A rule is a case label and the code after its arrow. - The rule produces
2. That number becomes the value of the wholeswitchexpression. - Java stores
2inprice. The last line readspriceand prints it.
Change drink to "coffee" and run the program again. It prints 3. Try "water". No case matches, so Java uses default, the rule for values that do not match a case. This time it prints 0.
The arrow alone does not tell you whether you’re looking at a statement or an expression. Look at where the switch is used. Here it sits to the right of =, where Java needs a value to store. Also notice the two kinds of semicolons: each short rule ends with one, and the semicolon after } ends the full line that sets price.
Use yield When a Case Needs Several Steps
A rule like case "tea" -> 2; can give Java a value in one step. A ticket price might take more work. For a child ticket, you might first name the discount, then subtract it from the base price.
A block is a group of code inside braces. When a rule uses a block, write yield before the value you want to give back to the switch expression. You can read yield basePrice - discount; as “use the result of this subtraction as the value of this switch.”
Save this program as TicketPricing.java.
public class TicketPricing {
public static void main(String[] args) {
int basePrice = 20;
String ticketType = "child";
if (args.length > 0) {
ticketType = args[0];
}
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 java TicketPricing.java. With nothing after the file name, ticketType stays set to "child". You can also run java TicketPricing.java adult. The extra word is a command-line argument, a value you pass to the program when you start it. In this example, args[0] reads the first such word if there is one.
For a child ticket, Java sets discount to 5. Then yield gives the switch the result of 20 - 5, which is 15. Java stores 15 in price. For an adult ticket, the short rule gives the switch the value of basePrice directly. It needs no yield.
The variable discount belongs to the child block. You can use it inside those braces, but you cannot read it after the switch. What the rest of the program gets is the number that the block yielded, stored in price.
What yield does and does not do
yield finishes the selected rule and supplies a value to the switch. It does not end the whole method. A method is a named group of code that carries out a task. In this example, the main method keeps going after the switch and prints the price. A return exits a method, so it is not a replacement for yield inside a rule block. A break does not supply a value either.
Printing is not the same as yielding. If you replace yield basePrice - discount; with System.out.println(basePrice - discount);, the block has no value to give the switch. Java rejects the program before it runs. A number on the screen cannot fill the price variable.
Cover Every Possible Case
A switch expression must be exhaustive. This means its rules must cover every possible choice Java checks for that selector. The compiler, the tool that checks and translates your Java code before it runs, enforces this rule. Even if you test only with "child", Java still checks what the expression can do with other values.
A String is Java’s type for text. There are too many possible text values to list them all as cases. In the examples here, default covers any text that does not match a rule. Remove default from TicketPricing.java and Java will reject it, even if you leave ticketType set to "child".
There are two useful ways to handle default:
- Give a fallback value if that value makes sense. For example, a shipping program could use the standard rate for any region that has no special rate.
- Report an error if there is no valid value to give. An unknown ticket type should not turn into a free ticket just because the program needs a number.
The ticket program uses throw for the second option. To throw an exception is to signal an error and stop the current path through the code. IllegalArgumentException is the name of a Java exception used when a supplied value is not valid. If the ticket type is "student", the program reports Unknown ticket type: student. It does not set price or run the print line. That still counts as handling the case: the program cannot reach the print line without a price.
| Command | What happens |
|---|---|
| `java TicketPricing.java` | The child block yields `15`, which the program prints. |
| `java TicketPricing.java adult` | The adult rule produces `20`, which the program prints. |
| `java TicketPricing.java student` | The program reports an error and prints no price. |
| `java TicketPricing.java Adult` | The program reports an error because `"Adult"` does not match `"adult"`. |
When you can leave out default
An enum is a Java type with a fixed list of named values. For example, a shop might offer only STANDARD and EXPRESS delivery. When a switch expression lists every named value of an enum, Java can see that the rules cover the full list and does not require default.
Save this program as DeliveryTimes.java and run java DeliveryTimes.java.
public class DeliveryTimes {
enum Delivery {
STANDARD, EXPRESS
}
public static void main(String[] args) {
Delivery choice = Delivery.EXPRESS;
int days = switch (choice) {
case STANDARD -> 5;
case EXPRESS -> 2;
};
System.out.println(days);
}
}The program prints 2. Now try adding OVERNIGHT to the Delivery list without adding a case. When you run the program again, Java checks the new code and reports that the switch is not exhaustive. Add case OVERNIGHT -> 1; to fix it. Set choice to Delivery.OVERNIGHT to test the new rule.
Leaving out default here helps catch a missed update. With a fallback rule, a new delivery option could pick up an old delivery time by mistake. Without one, Java asks you to choose a time for the new option before the program can run.
Check Every Path Inside a Block
A rule can cover a selector value and still fail to give the expression a result. A path is one route Java can take through your code. If a rule block has an if, check the path where the test is false as well as the path where it is true.
Suppose a group ticket costs 12 dollars per person for a group of ten or more. Smaller groups pay 16 dollars per person. Save this program as GroupRate.java and run java GroupRate.java.
public class GroupRate {
public static void main(String[] args) {
String ticketType = "group";
int groupSize = 8;
int pricePerPerson = switch (ticketType) {
case "group" -> {
if (groupSize >= 10) {
yield 12;
}
yield 16;
}
case "individual" -> 20;
default -> throw new IllegalArgumentException(
"Unknown ticket type: " + ticketType);
};
System.out.println(pricePerPerson);
}
}For a group of eight, the test is false. Java skips yield 12; and reaches yield 16;, so the program prints 16. For a group of ten, the test is true. Java reaches yield 12; and finishes the rule right there. It does not go on to yield 16;.
If you remove yield 16;, the path for a group of eight can reach the end of the block without giving a value. Java rejects the expression. The default rule cannot help: the selector already matched "group". These are two separate checks. First, does a rule cover the selector? Second, can the selected rule finish without giving a value or throwing an exception?
The values also need to fit where you use the expression. Here pricePerPerson is an int, Java’s type for whole numbers in a fixed range. If the individual rule gave "20" instead of 20, it would give text where Java needs a number. Both forms look alike on screen, but only 20 can fill this variable.
Diagnose a Switch Expression That Fails
Read the error message and check the part of the expression it points to. If the issue is not clear, trace one selector value at a time. Ask which rule it picks, what that rule gives back, and what happens next.
| What you notice | What to check |
|---|---|
| Java says the expression does not cover all possible values. | For text, check for a `default` rule. For an enum without `default`, check that every named value has a case. |
| Java says a rule block can finish without giving a value. | Follow each path through that block. Add the missing `yield`, or throw an exception if that path has no valid result. |
| Java expects a number but finds text. | Check the results of the short rules and the values after `yield`. Look for quotes around a number. |
| The program runs but picks the error rule for an input you expected to work. | Check the exact input text, including capital letters. For example, `"Adult"` and `"adult"` are different Strings. |
The key test is what happens after the switch. If the next line uses the result, each rule that finishes normally must give that line a usable value.
Practice
Exercise
In TicketPricing, change the base price to 24 and the child discount to 7. What does the program print for child, for adult, and for student?
Show answer
It prints 17 for child and 24 for adult. For student, it reports an unknown ticket type and prints no price.
Exercise
In GroupRate, change groupSize to 10. Which yield runs? Why does Java not reach the second one?
Show answer
yield 12 runs because 10 is at least 10. It finishes the selected rule and supplies the value of the switch, so the line with yield 16 does not run.
Exercise
A delivery program adds an enum value called PICKUP. You want Java to make you choose a delivery time for every new option. Should you add a default rule or add a case for PICKUP and leave default out?
Show answer
Add a case for PICKUP and leave default out. The rules cover the full list now, and Java will report a missing case if you add another option later.