Enums with Custom Numeric Values in Java

Enums in Java are used to represent a list of predefined values. Most of the time, you will probably not care about the associated value of an enum constant. In this scenario, you will write enums like this:

/**
 * Normal enum in which no custom numeric value is associated with enum member
 */
public enum SimpleHotelClassification {
    ONE_STAR,
    TWO_STAR,
    THREE_STAR,
    FOUR_STAR,
    FIVE_STAR
}

However, there might be times when you need to assign specific values to an enum constant, for example if you need to make some further queries or processing based on the enum value. The example below illustrates how to define a Java enum for storing a hotel classification. The number of stars for a given hotel is stored as a numeric value (1,2,3,4,5).

/**
 * Enum that provides a custom numeric value to the enum member
 */
public enum CustomHotelClassification {
    ONE_STAR(1),
    TWO_STAR(2),
    THREE_STAR(3),
    FOUR_STAR(4),
    FIVE_STAR(5);

    private final int value;

    // NOTE: Enum constructor must have private or package scope. You can not use the public access
    // modifier.
    private CustomHotelClassification(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

You can then retrieve the numeric value by calling the getValue() method.

for (CustomHotelClassification classification: CustomHotelClassification.values()) {
    System.out.println(classification + " with a value of " + classification.getValue());
}