Java

Java Enum Tutorial

Java enum is a special Java type that defines by a Java class. It is also called the Java enumeration type. It is introduced in Java version 5 first, which is mainly used to define the collection of constants. The compile type of safety is ensured by using the enum type. So, when all possible values of the variable are known before compile time, then it is better to use enum type. It defines a class that always extends from java.lang.Enum. How enum type can be declared and used in Java are shown in this tutorial.

Syntax:

public enum enum_name {

    value1, value2, … valueN
}

Here, enum keyword is used to declare enumeration type, and the values will be any constant value.  Different uses of enum type in Java are shown in the next part of this tutorial.

Example-1: Declare and iterate enum values

How enum values can be defined and accessed using the ‘for’ loop is shown in the following example. Here, seven-weekday names in the short form are assigned as enum values. Next, the ‘for’ loop is used to iterate each value from weekdays and print each value in each line as output.

public class enum1 {
   
    //Define the enum type
    public enum weekdays {
        Sun,Mon,Tue,Wed,Thu,Fri,Sat
    }
   
    //main() method
    public static void main(String[] args) {
        System.out.println("The short form of 7 weekdays are :");      
        //Iterating the values of enum
        for (weekdays day : weekdays.values()) {
            System.out.println(day);
        }  
    }
}

Output:

The following output will appear after executing the code.

Example-2: Using enum in the if-else statement

The following example shows the use of enum variable with the if-else-if statement. Here, an enum variable named courses is declared with four-course codes as values. The class contains a constructor that will initialize the variable named course by any enum value. Here, a course code will be provided at the time of object creation, and it will be checked with each ‘if’ condition and print the message where the condition returns true. If all the conditions return false, then the message from the else section will be printed.

public class enum2 {
   
    //Define the enum type
    public enum courses {
        CSE101,CSE205,CSE308,CSE407
    }
   
    //Declare a variable of enum type
    courses course;
   
    //Declare the constructor
    public enum2(courses course) {
        this.course = course;
    }
   
    a
    public static void main(String[] args) {
        //Declare an object
        enum2 object1 = new enum2(courses.CSE205);
       
        //Check the course value
        if(object1.course == courses.CSE101)
            System.out.print("The course name is Computer Fundamental");
        else if(object1.course == courses.CSE205)
            System.out.print("The course name is Data Structure");
        else if(object1.course == courses.CSE308)
            System.out.print("The course name is Operating System");
        else if(object1.course == courses.CSE407)
            System.out.print("The course name is Unix Programming");
        else
            System.out.print("Course code does not exist");
           
    }
}

Output:

In the above code, enum value, CSE205 is provided at the time of object creation that matched with the second ‘if’ condition and printed the message, “The course name is Data Structure.”

Example-3: Using enum with constructor and method

How enum constructor and enum method can be defined and used in java are shown in the following example. The twelve enum values with codes are defined with the twelve months in the short form. A constructor of an enum with a parameter is declared in the code that initializes the private integer variable named mCode. A enum method named readMCode() is declared to return the values of mCode. In the main() method, six variables are declared and initialized with empty string to store the particular enum values based on the switch-case values. Here, the ‘for’ loop is used to iterate each enum value and declare an enum object based on each value. When any enum object is created, then the code of the corresponding enum value will be initialized to mCode. The return value of the readMCode() method will be used in the switch to match with case values. Here, a particular block of statements is defined for two case values. For example, 0 and 1 will be returned as mCode for the months, JAN and FEB. These two month’s names will be stored in the variable s1 and printed the value by combining with other string. The same task will be done with the other five variables, s2, s3, s4, s5, and s6, for the other ten months.

According to the code, Winter will be printed for the month JAN and FEB. Spring will be printed for the month of MAR and APR. Summer will be printed for the month of MAY and JUN. Rainy Season will be printed for the month of JUL and AUG. Autumn will be printed for the month of SEP and OCT and Late Autumn will be printed for the month of NOV and DEC.

public class enum3 {
   
    public enum Months {
         JAN(0),FEB(1),MAR(2),ARP(3),MAY(4),JUN(5),
         JUL(6), AUG(7),SEP(8),OCT(9),NOV(10),DEC(11);

        private int mCode;
       
        //enum constructor
        Months(int mCode) {
            this.mCode = mCode;
        }
       
        //enum method
        public int readMCode() {
            return this.mCode;
        }
       
    }
       
    //main() method
    public static void main(String[] args) {
       
        //Initialize variables
        String s1="",s2="",s3="",s4="",s5="",s6="";
        //Iterating the values of enum
        for (Months month : Months.values()) {
            //Declare enum object
            Months m = month;
            switch(m.readMCode())
            {
                  case 0:
                case 1:
                    if(s1.equals(""))
                        s1=month.toString();
                    else {
                        s1+=" and "+month.toString();
                        System.out.println(s1+" are Winter.");
                    }
                    break;
                case 2:
                case 3:
                    if(s2.equals(""))
                        s2=month.toString();
                    else {
                        s2+=" and "+month.toString();
                        System.out.println(s2+" are Spring.");
                    }
                    break;
                case 4:
                case 5:
                    if(s3.equals(""))
                        s3=month.toString();
                    else {
                        s3+=" and "+month.toString();
                        System.out.println(s3+" are Summer.");
                    }
                    break;
                case 6:
                case 7:
                    if(s4.equals(""))
                        s4=month.toString();
                    else {
                        s4+=" and "+month.toString();
                        System.out.println(s4+" are Rainy Season.");
                    }
                    break;
                case 8:
                case 9:
                    if(s5.equals(""))
                        s5=month.toString();
                    else {
                        s5+=" and "+month.toString();
                        System.out.println(s5+" are Autumn.");
                    }
                    break;
                case 10:
                case 11:
                    if(s6.equals(""))
                        s6=month.toString();
                    else {
                        s6+=" and "+month.toString();
                        System.out.println(s6+" are Late Autumn.");
                    }
                    break;
               }
            }
     }
}

Output:

The following output will appear after executing the above code.

Conclusion:

When we need to work with the constant data, then it is better to use the enum variable. The different uses of enum datatype are explained in this tutorial to learn the benefits of using enumeration type in Java.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.