Switch on enum (with examples)
Java has support for switching on enum values.
switch (month) { case FEB: System.out.println("28 days"); break; case APR: case JUN: case SEP: case NOV: System.out.println("30 days"); break; default: System.out.println("31 days"); }
enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } public class EnumDemo { static void printNumDays(Month month) { switch (month) { case FEB: System.out.println("28 days"); break; case APR: case JUN: case SEP: case NOV: System.out.println("30 days"); break; default: System.out.println("31 days"); } } public static void main(String[] args) { printNumDays(Month.FEB); // 28 days printNumDays(Month.JUN); // 30 days printNumDays(Month.DEC); // 31 days } }
You must not fully qualify the constants. This will not compile: case Month.FEB: …
Arrow Syntax
With Java 14+ the above switch statement can be written as:
static void printNumDays(Month month) {
switch (month) {
case FEB -> System.out.println("28 days");
case APR, JUN, SEP, NOV -> System.out.println("30 days");
default -> System.out.println("31 days");
}
}
Or using a switch expression:
static void printNumDays(Month month) {
int days = switch (month) {
case FEB -> 28;
case APR, JUN, SEP, NOV -> 30;
default -> 31;
};
System.out.println(days + " days");
}
See Switch Statement and Switch Expression for more examples.
Comments
Be the first to comment!