Sunday, September 30, 2012

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

Java Enum in Switch Case Statement
Yesterday, some one 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 Switch case with Enum. Using Java Enum in 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

How to use Enum in Switch case in Java with Example
In this example of using Enum in Switch case, we have create a Days of Week Enum which represent 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 those 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 body of for loop we have create 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 same class you can use there instance without calling them with class name e.g. MONDAY . Here is complete code example of using Enum in Switch case in Java :

/**
 *
 * 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 name(), cardinal(), values() etc, which will help you to get most of Java Enum apart from just using Enum in Switch case.

Other Java tutorials from Java67

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

Java67 Headline Animator