Java - Enum Enum Types

What Is an Enum Type?

An enum create an ordered list of constants as a type.

Syntax

You define an enum type using the keyword enum.

Its simplest general syntax is

<access-modifier> enum <enum-type-name> {
    // comma separated names of enum constants
}
  • The value for <access-modifiers> are one of: public, private, protected, or package-level.
  • <enum-type-name> is a valid Java identifier.

The following code declares an enum type called Gender, which declares two constants, MALE and FEMALE:

public enum Gender {
   MALE, FEMALE; // The semi-colon is optional in this case
}

The following code declares a public enum type called Level with four enum constants: LOW, MEDIUM, HIGH, and URGENT.

public enum Level {
        LOW, MEDIUM, HIGH, URGENT;
}

You declare a variable of an enum type the same way you declare a variable of a class type.

// Declare defectLevel variable of the Level enum type
Level defectLevel;

You can assign null to an enum type variable, like so:

Level defectLevel = null;

The following snippet of code assigns values to a variable of Level enum type:

Level low = Level.LOW;
Level medium = Level.MEDIUM;
Level high = Level.HIGH;
Level urgent = Level.URGENT;

ordinal

An enum type assigns an order number (or position number), called ordinal, to all of its constants.

The ordinal starts with zero and it is incremented by one as you move from first to last in the list of constants.

The following code prints the name and ordinal of all enum constants declared in the Level enum type.

Demo

enum Level {
        LOW, MEDIUM, HIGH, URGENT;/*from w  ww.  j ava2  s .c om*/
}
public class Main {
        public static void main(String[] args) {
                for(Level s : Level.values()) {
                        String name = s.name();
                        int ordinal = s.ordinal();
                        System.out.println(name + "(" + ordinal + ")");
                }
        }
}

Result

Related Topics