Construction. Larger types and the default case for switch
[comp1110-78]
The switch statements/expressions do not just work on enum values - in fact, they can distinguish between values of a wide variety of types.
Modern Java uses them to implement a kind of pattern-matching you might be used to from Haskell (but do not worry if you are not - if at all, we will only see that towards the end of this course).
You can also use them on strings or integers.
But those have many possible values - you don't really want to be writing cases for each and every one of them!
Any switch statement or expression can contain a default case for all other values not captures by previous cases.
In addition, individual cases can capture multiple values, like so:
boolean isSummer(Month m) {
return switch(m) {
case DECEMBER, JANUARY, FEBRUARY -> true;
default -> false;
};
}
And similarly, you can do the same for Strings:
boolean isSummer(String m) {
return switch(m) {
case "Dec", "Jan", "Feb" -> true;
default -> false;
};
}
The main difference here is that the latter works for all kinds of Strings, so you need to be careful about what your catch-all default case expresses. Here, the string "December" would return false, too!