Wednesday, January 22, 2025
HomeProgrammingHow To Switch case with enum in Java

How To Switch case with enum in Java

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:

  1. Switching on enum: You directly use the enum constants (e.g., Day.MONDAY, Day.TUESDAY, etc.) in the switch case.
  2. default case: Even though the switch is on an enum, it’s a good practice to include a default case, although all possible enum values are covered.
  3. Type Safety: The enum ensures type safety, meaning you can only switch on values defined within the enum itself, avoiding invalid values.
See also  C Header Files

Output:

It's Monday!

This approach can easily be extended or modified for other enum types.

RELATED ARTICLES

C Function Pointers

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

C Function Pointers

List of Asian Countries

Recent Comments

0
Would love your thoughts, please comment.x
()
x