Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 193
Covering All Possible Values
ОглавлениеThe last rule about switch
expressions is probably the one the exam is most likely to try to trick you on: a switch
expression that returns a value must handle all possible input values. And as you saw earlier, when it does not return a value, it is optional.
Let's try this out. Given the following code, what is the value of type
if canis
is 5
?
String type = switch(canis) { // DOES NOT COMPILE case 1 -> "dog"; case 2 -> "wolf"; case 3 -> "coyote"; };
There's no case
branch to cover 5
(or 4
, -1
, 0
, etc.), so should the switch
expression return null
, the empty string, undefined, or some other value? When adding switch
expressions to the Java language, the authors decided this behavior would be unsupported. Every switch
expression must handle all possible values of the switch
variable. As a developer, there are two ways to address this:
Add a default branch.
If the switch expression takes an enum value, add a case branch for every possible enum value.
In practice, the first solution is the one most often used. The second solution applies only to switch
expressions that take an enum. You can try writing case
statements for all possible int
values, but we promise it doesn't work! Even smaller types like byte
are not permitted by the compiler, despite there being only 256 possible values.
For enums, the second solution works well when the number of enum values is relatively small. For example, consider the following enum definition and method:
enum Season {WINTER, SPRING, SUMMER, FALL} String getWeather(Season value) { return switch(value) { case WINTER -> "Cold"; case SPRING -> "Rainy"; case SUMMER -> "Hot"; case FALL -> "Warm"; }; }
Since all possible permutations of Season
are covered, a default
branch is not required in this switch
expression. You can include an optional default
branch, though, even if you cover all known values.
What happens if you use an enum with three values and later someone adds a fourth value? Any switch
expressions that use the enum without a default
branch will suddenly fail to compile. If this was done frequently, you might have a lot of code to fix! For this reason, consider including a default
branch in every switch
expression, even those that involve enum values.