Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Handling Enumerations in Java

In this article well see a brief introduction to Java Enumerations, that are very useful to list constant things in the language.

An enum is a data type (reference type or special Java type) which defines a variable with predefined constants. The variable must be equal to one of the values that have been predefined for it. The names of an enum type's fields are in uppercase letters, because they are constants. The enum keyword is used to define the enum type. You should use enum types any time you need to represent a fixed set of constants.

For example:

public enum Month {
    // enum keyword is used to define an enum
    // Month enum constants are declared
    JANUARY, // each constant declaration is separated by , (comma)
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
    // ; semicolon is optional only if there are no any other enum members
    // defined.
    // If enum has other members like constructors, methods then
    // ; semicolon is required after the end of enum constants declaration.
}

Here Monthenum can have any value defined in the enum definition. An enum is not a String or an int; an enum constant's type is the enum type. Here JANUARY is not the String type, it’s an enum type Month.

Conceptually enum means

Let's see the following example:

public class Month {
    
    public String name;
    public int ordinal;
    
    private Month(String enum_name, int index){
        this.name = enum_name;
        this.ordinal = index;
    }    
    
    public static final Month JANUARY = new Month("JANUARY",0);
    public static final Month FEBRUARY = new Month("FEBRUARY",1);
    public static final Month MARCH = new Month("MARCH",2);
    public static final Month APRIL = new Month("APRIL",3);
    public static final Month MAY = new Month("MAY",4);
    public static final Month JUNE = new Month("JUNE",5);
    public static final Month JULY = new Month("JULY",6);
    public static final Month AUGUST = new Month("AUGUST",7);
    public static final Month SEPTEMBER = new Month("SEPTEMBER",8);
    public static final Month OCTOBER = new Month("OCTOBER",9);
    public static final Month NOVEMBER = new Month("NOVEMBER",10);
    public static final Month DECEMBER = new Month("DECEMBER",11);
    
    public String toString(){
        return name;
    }
}

Enum is just like a class. Each enum constant is the public static final instance variable of the class of same class type. These instance variables are initialized by the instance of the class by passing below two arguments.

  1. Name of the enum (it’ll be same as the enum constant name)
  2. Index of the enum (it’ll be same as the enum constant position start from 0 )

When this class loads in the memory the instance variable will get memory on heap and it’ll be initialized by given value.

Here is some code that shows you how to use the Month enum defined above:

public class TestEnum {
    private Month month; // 1
    
    public TestEnum(Month month) { // 2
        this.month = month;
    }
    
    private void printMonth(Month month) { // 3
        int monthNo = month.ordinal() + 1; // 4
        System.out.println("Month No: " + monthNo + "\t Month Name : " + month.name());// 5
    }
    
    private void displayMonthInfo() {
        switch (month) { // 6
            case JANUARY:
            printMonth(month);
            break;
            case FEBRUARY:
            printMonth(month);
            break;
            case MARCH:
            printMonth(month);
            break;
            case APRIL:
            printMonth(month);
            break;
            case MAY:
            printMonth(month);
            break;
            case JUNE:
            printMonth(month);
            break;
            case JULY:
            printMonth(month);
            break;
            case AUGUST:
            printMonth(month);
            break;
            case SEPTEMBER:
            printMonth(month);
            break;
            case OCTOBER:
            printMonth(month);
            break;
            case NOVEMBER:
            printMonth(month);
            break;
            case DECEMBER:
            printMonth(month);
            break;
        }
    }
    
    private static void printResult(Month month) {
        new TestEnum(month).displayMonthInfo();
    }
    
    public static void main(String[] args) {
        for (Month month : Month.values()) { // 7
            printResult(month); // 8
        }
    }
}

  1. A field of type Month (Month is an enum type) is declared.
  2. A constructor is defined using an enum parameter.
  3. A method is defined using an enum parameter.
  4. ordinal() returns the ordinal value of this enum constant starting from zero.
  5. name() returns the name of this enum constant, exactly as declared in its enum declaration.
  6. Enum can be used in the switch case condition
  7. values() returns an array containing the enum constants of this enum type, in the order they are specified.
  8. Print the result as below:

Month No: 1     Month Name : JANUARY
Month No: 2     Month Name : FEBRUARY
Month No: 3     Month Name : MARCH
Month No: 4     Month Name : APRIL
Month No: 5     Month Name : MAY
Month No: 6     Month Name : JUNE
Month No: 7     Month Name : JULY
Month No: 8     Month Name : AUGUST
Month No: 9     Month Name : SEPTEMBER
Month No: 10    Month Name : OCTOBER
Month No: 11    Month Name : NOVEMBER
Month No: 12    Month Name : DECEMBER

An enum can be declared outside or inside a class, but NOT in a method. An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.

Above Month enum is the enum declared outside a class. We can save this file as Month.java file name.

An enum declared inside a class as below:

public class ScoreSystem {
    enum Marks {
        A, B, C, D, E
    } // ; semicolon is optional
    
    public static void main(String[] args) {
        // enum Marks {A, B, C, D, E}
        // compile time error: The member enum Month
        // can only be defined inside a top-level class or interface
        System.out.println(Marks.A); // A
        System.out.println(Marks.A.name()); // A
        System.out.println(Marks.A.ordinal()); // 0
        System.out.println(Marks.A.toString()); // A
    }
}

Apart from the enum constants the enum can declare constructors and other class members like method, variables and constant’s class body. Enum constants must be declared before any other declaration. Enum constants can send arguments to the enum constructor as like below:

A(98, “Excellent”) 

Here 98 and Excellent will be passed to the enum constructor. Enum constructors can have arguments, and can be overloaded. Enum constructors can NEVER be invoked directly in code. They are always called automatically when enum constant is initialized. (enum constant is initialized at enum loading time because enum constant is public static final instance variable of enum). The constructor for an enum type must be package-private or private access.

The semicolon at the end of an enum declaration is optional. These are legal:

enum ShowNumber { ONE, TWO, THREE}
enum ShowNumber { ONE, TWO, THREE};

Enum can have constant’s class body. Enum constant’s class body is specific to a particular enum constant. It’s enclosed inside { }. “{” starts immediately after the enum constant or after the argument constructor. The class bodies can contain member’s declaration and definition. Constructor, abstract method and static methods can’t be inside a constant’s class body. If enum type contains any abstract method then each enum constant has to override that method inside the constant’s class body. Instance methods declared in constant-specific class bodies are only accessible if they override methods in the enclosing enum super type.

Example of enum with constructor, method and constant’s class body.

import java.util.Arrays;

public enum DailyRoutine {
    WAKEUP("Wake Up", 6, 0), // enum constants with arguments
    FRESHENUP("Freshen Up", 6, 6.30) { // enum constant’s class body started
        @Override
        public String show() {
            return this.toString() + " \t " + start + " to " + end;
        } // enum constant’s class body ended
    },
    
    EXERCISE("Exercise", 6.30, 7.00) {
        @Override
        public String show() {
            return this.toString() + " \t " + start + " to " + end;
        }
    },
    
    BATH("Bath", 7.30, 8.00), BREAKFAST("Breakfast", 8.00, 8.30) {
        @Override
        public String show() {
            return this.toString() + " \t " + start + " to " + end;
        }
    },
    OFFICE(9, 18), LUNCH(12.30, 13.30), TEA(5, 5.30), MEDITATION("Meditation", 6.30, 7.30) {
        @Override
        public String show() {
            return this.toString() + " \t " + start + " to " + end;
        }
    },
    SKILLIMPROVEMENT("Skill Improvement", 7.30, 8.30) {
        @Override
        public String show() {
            return this.toString() + "\t " + start + " to " + end;
        }
    },
    DINNER(8.30, 9.00), NIGHTREADING("Night Reading", 9.30, 10.30) {
        @Override
        public String show() {
            return this.toString() + " \t " + start + " to " + end;
        }
    },
    SLEEP(10.30, 6);
    
    /* variables declared inside enum */
    String value;
    double start;
    double end;
    
    // enum constructor
    DailyRoutine(double start, double end) {
        this.start = start;
        this.end = end;
    }
    
    // enum overloaded constructor
    DailyRoutine(String value, double start, double end) {
        this(start, end);
        this.value = value;
    }
    
    // method inside enum
    public String show() {
        return this.toString() + " \t\t " + start + " to " + end;
    }
    
    @Override
    public String toString() {
        if (this.value == null) {
            return this.name();
        }
        return this.value;
    }
    
    public static void main(String[] args) {
        System.out.println(Arrays.asList(DailyRoutine.values()));//1
        for (DailyRoutine d : DailyRoutine.values()) {
            System.out.println(d.show());//2
        }
    }
}

1. print result as below

 [Wake Up, Freshen Up, Exercise, Bath, Breakfast, OFFICE, LUNCH, TEA, Meditation, Skill Improvement, DINNER, Night Reading, SLEEP] 

2. print result as below

Wake Up           6.0 to 0.0
Freshen Up        6.0 to 6.3
Exercise          6.3 to 7.0
Bath              7.3 to 8.0
Breakfast         8.0 to 8.3
OFFICE            9.0 to 18.0
LUNCH             12.3 to 13.3
TEA               5.0 to 5.3
Meditation        6.3 to 7.3
Skill Improvement 7.3 to 8.3
DINNER            8.3 to 9.0
Night Reading     9.3 to 10.3
SLEEP             10.3 to 6.0

All enum types are subtypes of the java.lang.Enum class. All enum types are comparable and serializable.

All enum types inherit the following final methods from the java.lang.Enum class, and these methods can therefore not be overridden by an enum type:

public abstract class java.lang.Enum extends java.lang.Object implements java.lang.Comparable,java.io.Serializable{
    public final java.lang.String name();
    public final int ordinal();
    protected java.lang.Enum(java.lang.String, int);
    public java.lang.String toString();
    public final boolean equals(java.lang.Object);
    public final int hashCode();
    protected final java.lang.Object clone() throws java.lang.CloneNotSupportedException;
    public final int compareTo(java.lang.Enum);
    public final java.lang.Class getDeclaringClass();
    public static java.lang.Enum valueOf(java.lang.Class, java.lang.String);
    protected final void finalize();
    public int compareTo(java.lang.Object);
}

public final String name()

Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString() method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

public final int ordinal()

This method returns the ordinal value of this enum constant (that is, its position in its enum type declaration). The first enum constant is assigned an ordinal value of zero. If the ordinal value of an enum constant is less than the ordinal value of another enum constant of the same enum type, the former occurs before the latter in the enum type declaration.

protected final Object clone()

An instance of an enum type cannot be cloned. The method throws an CloneNotSupportedException.

protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

Throws CloneNotSupportedException. This guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.

final int compareTo(E o)

Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.

public final boolean equals(Object other)

This method returns true if the specified object is equal to this enum constant.

For any two enum references dr1 and dr2, the expression dr1.equals(dr2) and dr1 == dr2 are equivalent.

protected final void finalize()

An enum constant cannot be finalized, because this final method effectively prevents enum types from implementing their own finalize() method.

public final Class getDeclaringClass()

Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass method for enum constants with constant-specific class bodies.)

public final int hashCode()

This method returns a hash code for this enum constant.

All enum types implicitly have the following static methods, and methods with these names cannot be declared in an enum type declaration:

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

public static T[] values()

Returns an array containing the enum constants of this enum type, in the order they are specified.

public static T valueOf(String name)

Returns the enum constant with the specified name. An IllegalArgumentExceptionis thrown if the specified name does not match the name of an enum constant.

The specified name is not qualified with the enum type name.

An enum type cannot be explicitly extended using the extends clause. An enum type is implicitly final, unless it contains constant-specific class bodies. If it declares constant-specific class bodies, it is implicitly extended. No matter what, it cannot be explicitly declared final.

All enums implicitly extendjava.lang.Enum. Because a class can only extend one parent the Java language does not support multiple inheritance of state, and therefore an enum cannot extend anything else.

Like a class, an enum can implement interfaces.

public interface ITimeInfo {
    public int getHour();
    public int getMins();
}

public enum Meal implements ITimeInfo{
    ...
    public int getHour() { return this.hh; }
    public int getMins() { return this.mm; }
}



5+ yrs of experience on Java/JEE.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login