In Java, switching on an enum
type is similar to switching on integers or strings, but it has some advantages. Since enum
constants are of a specific type, you can use them directly in the switch
statement. Here’s how you can do it:
Example with enum
in switch
:
First, define your enum
type:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Then, you can use a switch
statement to handle different enum values:
public class EnumSwitchExample {
public static void main(String[] args) {
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("It's Monday!");
break;
case TUESDAY:
System.out.println("It's Tuesday!");
break;
case WEDNESDAY:
System.out.println("It's Wednesday!");
break;
case THURSDAY:
System.out.println("It's Thursday!");
break;
case FRIDAY:
System.out.println("It's Friday!");
break;
case SATURDAY:
System.out.println("It's Saturday!");
break;
case SUNDAY:
System.out.println("It's Sunday!");
break;
default:
System.out.println("Invalid day");
break;
}
}
}
Key Points:
- Switching on
enum
: You directly use theenum
constants (e.g.,Day.MONDAY
,Day.TUESDAY
, etc.) in theswitch
case. default
case: Even though the switch is on anenum
, it’s a good practice to include adefault
case, although all possible enum values are covered.- Type Safety: The
enum
ensures type safety, meaning you can only switch on values defined within theenum
itself, avoiding invalid values.
Output:
It's Monday!
This approach can easily be extended or modified for other enum
types.