How to use Java Enum in Switch Case Statement

How to use Java Enum in Switch Case Statement?

How to use Java Enum in Switch Case Statement?

We have seen Basics of Java Enum and its important functions in our earlier session. Also we have seen how to convert String to Enum and Enum to String in our last session. Today we are going to see one important concept about Java Enum. Before going into the concept, let’s start from one simple question. Can we use String in Switch case? Prior to Java 7 we can’t use String in Switch case statement. Only from Java 7 we have the provision to use String in Switch case. But prior to Java 7, how can we achieve String comparison in Switch statement? The answer is Java Enum, confused right? Now we have another question How to use Java Enum in Switch Case Statement.

In this tutorial we will see how to use Java Enum in Switch case statement along with some example.

Java Enum in Switch Case Statement

Using Java Enum in a project is Switch case statement is quite popular in IT industry nowadays. Also well experienced Java Professional will say using Java Enum in Switch case as one of the best coding practice.  Now we will see with one example.

Days.java

package com.learnfromexamples.enumtutorial.pkg5.switchcase;

public enum Days {
    MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY
}

DaysSwitchImplementation .java

package com.learnfromexamples.enumtutorial.pkg5.switchcase;

public class DaysSwitchImplementation {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String day = "MONDAY";
        Days days = Enum.valueOf(Days.class, day);
        switch (days) {
        case MONDAY:
            System.out.println("Today is monday");
            break;
        case TUESDAY:
            System.out.println("Today is tuesday");
            break;
        case WEDNESDAY:
            System.out.println("Today is wednesday");
            break;
        case THURSDAY:
            System.out.println("Today is thursday");
            break;
        case FRIDAY:
            System.out.println("Today is friday");
            break;
        default:
            break;
        }
    }

}

Output


Today is monday

When we see the code snippet we are passing a string called “MONDAY” , later we convert it into Days Enum type and we use that in switch case also. So to achieve string comparison in switch case we can use Enum as a better option.