How to use Java Enum in Switch Case Statement - Exampel Tutorial

Java Enum in Switch Case Statement
Yesterday, someone ask me Can we use Java Enum in Switch case? Obviously, he was learning Enum and not aware that How powerful Enum in Java is. Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to  use the Switch case with Enum. Using Java Enum in the Switch case is pretty straightforward, Just use Enum reference variable in Switch and Enum constants or instances in CASE statement. In this Java tutorial we will see one example of How to use Enum in Switch statement in Java

By the way Enum is feature rich in Java, Enum can implement interface in Java, Enum can override method in Java, Enum can have constructor in Java and Enum is full functional Type like class or interface.

Programmers use Enum with different ways. One of the best example of Enum in Java is replace enum int pattern and enum String pattern. You can also use Enum to write Thread-safe Singleton in Java.



Enum in Switch case - Java

In this example of using Enum in Switch case, we have created a Days of Week Enum which represents all days e.g. Monday, Tuesday etc. Then we get all Enum instances in an array using Enum.values() method and by using advanced for loop of Java 5, we loop through each of that Enum instance. 

By the way, you can also use String in Switch case from Java7 onwards. Similarly, you can also convert Enum to String in Java.

In the body of for loop, we have created a switch case statement using Enum in Java. Which switch on current Enum instance and every CASE statement is individual Enum instance e.g. DAY.MONDAY or DAY.TUESDAY

Since you have declared Enum in the same class you can use their instance without calling them with class name e.g. MONDAY. Here is a complete code example of using Enum in Switch case in Java :



How to use Enum in Switch case in Java with Example/**
 *
 * Java program to demonstrate how to use Enum in Switch case statement.
 * Enum can be used in switch block similar to primitive int or enum int pattern.
 * Enum can also be used in CASE statement to take appropriate action based upon
 * Enum instance.
 *
 * @author Javin
 */

public class EnumInSwitch {

    public enum Day {

        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    }

    public static void main(String args[]) {

        Day[] daysOfWeek = Day.values();

        for (Day today : daysOfWeek) {

            //Using Enum in Switch case statement

            switch (today) {
                case MONDAY:
                    System.err.println("Today is Monday learn example of How to use Java Enum in Switch");
                    break;
                case TUESDAY:
                    System.err.println("Tuesday, apply Enum in Switch just link primitive int");
                    break;
                case WEDNESDAY:
                    System.err.println("Wednesday, I confirm Java Enum can be used in Switch case");
                    break;
                case THURSDAY:
                    System.err.println("Thursday, Java Enum values() method return all enum in an array");
                    break;
                case FRIDAY:
                    System.err.println("Friday, Enum can also be used in case statement");
                    break;
                case SATURDAY:
                    System.err.println("Saturday, Enum in Java are compile time constant");
                    break;
                case SUNDAY:
                    System.err.println("Sunday, Using Enum in Switch is very easy");
                    break;

            }
        }
    }
}

Output:
Today is Monday learn example of using Java Enum in Switch
Tuesday, apply Enum in Switch just link primitive int
Wednesday, I confirm Java Enum can be used in Switch case
Thursday, Java Enum values() method return all enum in an array
Friday, Enum can also be used in case statement
Saturday, Enum in Java are compile time constant
Sunday, Using Enum in Switch is very easy


That's all on How to use Enum in Switch case in Java. Its indeed very easy and after trying it one time , you will be familiar with that. Just get yourself familiar with Enum API and some useful methods like the name(), cardinal(), values() etc, which will help you to get most of Java Enum apart from just using Enum in Switch case.


Related Java Enum Tutorials for further reading :
  1. Top 15 Java Enum Interview Questions with Answers (see here)
  2. Difference between RegularEnumSet and JumboEnumSet in Java (read here)
  3. String to Enum in Java with Example (check here)
  4. Can we use Enum in Switch Statement in Java (Yes)
  5. How to use valueOf method of Enum (check here)
  6. What Every Java Programmer Should know about Enum (click here)
  7. 10 points about Enum in Java (see here)
  8. How to loop over Enum constants in Java (example)
  9. Learn how to use Enum in Java with a Simple Example (check here)
  10. Java tip to convert  Enum to String in Java (see tip)
  11. Can Enum have Constructor in Java (learn here)
  12. 10 Courses to learn Java for Beginners (courses)
Thanks for reading this article so far. If you find this article useful then please share it on Facebook, Twitter, and LinkedIn. 

5 comments:

  1. Hi,

    Great blog! Is there an email address I can contact you in private?

    ReplyDelete
  2. thanks for your sharing about switch case in jaVa

    ReplyDelete
  3. You can also use Switch case directly with String from Java 1.7 onwards, but still using Enum and Switch case is much better of overall code quality as, String are brittle and case sensitive.

    ReplyDelete
  4. For those, who wants to learn more, Enum in Switch case is implemented using ordinal() method. Since as per Java programming language, we can only pass int into Switch case, ordinal() returns int. So above code of Enum with Switch will actually translate into

    switch(today.ordinal()){

    case Monday.ordinal():
    break;

    case Tuesday.ordinal():
    break;
    }



    ReplyDelete
    Replies
    1. if switch is to take only int, how can it accept String (java 1.7 onwards)

      Delete

Feel free to comment, ask questions if you have any doubt.