Coding

Enum in Java: Syntax, Methods and Examples

An enum in Java is a special type whose variables can hold only one of a fixed set of named constants: public enum Day { MONDAY, TUESDAY, WEDNESDAY }. You declare it with the enum keyword, refer to the constants as Day.MONDAY, and can give it fields, constructors and methods like a class.

Enum in Java: basic syntax

The Oracle Java tutorial defines an enum type as "a special data type that enables for a variable to be a set of predefined constants". The variable must equal one of the values you declared. Because they are constants, the names are written in uppercase letters by convention.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

Use it like any other type:

Day today = Day.WEDNESDAY;
System.out.println(today);

Example output: WEDNESDAY. You never write new Day(...). The constants are created for you, and the constructor cannot be called from your code. Like a class, a public enum goes in a file named after it (Day.java), or you can nest it inside another class.

Use an enum in a switch statement

Enums and switch work well together, because the compiler knows the full list of possible values. Inside the case labels you write the bare constant name, without the enum name in front:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekends are best.");
                break;
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }
}

This is the example from the Oracle tutorial. Calling it with Day.MONDAY prints Mondays are bad., and Day.FRIDAY prints Fridays are better. The break statements matter: without one, execution falls through to the next case. The stacked SATURDAY and SUNDAY labels share one body on purpose. If you are new to loops and branches in Java, the Java for loop article covers the other half of everyday control flow.

Loop over all values with values()

The compiler adds a static method values() to every enum. It returns an array of all the constants in the order they were declared, and it is commonly used with the for-each loop:

for (Day day : Day.values()) {
    System.out.println(day);
}

Example output starts with SUNDAY, then MONDAY, and so on through SATURDAY. The order is the declaration order, so if the order matters to you, declare the constants in that order. If you need to work with arrays more generally, see Java arrays: declare, initialize and loop.

Enum with fields, a constructor and methods

An enum is more than a list of names. It is a kind of class, so each constant can carry data. The Oracle tutorial shows this with a Planet enum. Here is a smaller version of the same idea:

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6);

    private final double mass;    // in kilograms
    private final double radius;  // in meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
}

Three rules from the tutorial explain this layout:

  • Constants come first. Java requires the constants to be defined before any fields or methods. When there are fields and methods, the list of constants must end with a semicolon, as after EARTH(...) above.
  • The arguments in parentheses call the constructor. EARTH (5.976e+24, 6.37814e6) creates the EARTH constant by passing those two numbers to Planet(double mass, double radius).
  • The constructor must be package-private or private. The tutorial says it "automatically creates the constants that are defined at the beginning of the enum body" and that you cannot invoke it yourself. That is what guarantees the set of constants is fixed.

Marking the fields private final keeps each constant immutable, which is the usual choice because constants are shared across your whole program. Calling Planet.EARTH.surfaceGravity() then works like calling a method on any object.

Methods every enum has

All enums implicitly extend java.lang.Enum, so they inherit its methods. The Java SE 21 API documentation describes these:

MethodWhat it does
values()Static, added by the compiler. Returns all constants in declaration order.
valueOf(String)Static, added by the compiler. Returns the constant whose declared name matches the string exactly.
name()Returns the constant's name exactly as declared. It is final.
toString()Returns the name by default. An enum can override it to return something friendlier.
ordinal()Returns the position in the declaration, starting at zero.
compareTo(E)Compares by declaration order. Only constants of the same enum type can be compared.

A short demonstration:

enum Color { RED, GREEN, BLUE }

Color c = Color.valueOf("GREEN");
System.out.println(c.name());     // GREEN
System.out.println(c.ordinal());  // 1
System.out.println(c.compareTo(Color.BLUE));  // a negative number

GREEN is declared second, so its ordinal is 1. It is declared before BLUE, so compareTo returns a negative integer.

Convert a string to an enum with valueOf()

valueOf is the standard way to turn text, for example from a config file or a request parameter, into an enum constant. The name must match an identifier used to declare a constant exactly. The API documentation states that extraneous whitespace is not permitted, so "GREEN " with a trailing space fails.

Color d = Color.valueOf("GREEN");   // Color.GREEN
Color e = Color.valueOf("BLUE");    // Color.BLUE
Color f = Color.valueOf("PURPLE");  // throws IllegalArgumentException

If there is no constant with that name, the call throws IllegalArgumentException. Passing null throws NullPointerException. Case also matters: valueOf("green") fails for a constant declared as GREEN. When the string comes from outside your program, catch IllegalArgumentException and report a clear error, or loop over values() and compare names yourself if you want to accept other spellings.

Override toString() for readable names

The documentation says toString() may be overridden, and that an enum should override it when a more programmer-friendly string form exists. It also advises that most programmers should prefer toString() over name() for display, because name() is meant for cases where correctness depends on the exact declared name.

public enum Level {
    LOW("Low priority"),
    HIGH("High priority");

    private final String label;

    Level(String label) {
        this.label = label;
    }

    @Override
    public String toString() {
        return label;
    }
}

Now System.out.println(Level.HIGH) prints High priority, while Level.HIGH.name() still returns HIGH, and Level.valueOf("HIGH") still works. Parse with the name, display with toString(), and the two never get mixed up.

EnumMap: a map keyed by an enum

When you need to associate data with each constant, java.util.EnumMap is built for that. The API documentation says all keys must come from a single enum type, that the map is represented internally as arrays, and that this representation is "extremely compact and efficient". Basic operations run in constant time and are likely, though not guaranteed, to be faster than their HashMap counterparts.

import java.util.EnumMap;
import java.util.Map;

Map<Day, String> plan = new EnumMap<>(Day.class);
plan.put(Day.FRIDAY, "Release");
plan.put(Day.MONDAY, "Planning");

System.out.println(plan);

Example output: {MONDAY=Planning, FRIDAY=Release}. Even though FRIDAY was inserted first, iteration follows the order the constants are declared, not insertion order. Null keys are not permitted: inserting one throws NullPointerException, although null values are allowed. The constructor takes the enum's Class object, which is how the map knows which constants are possible.

Limits of enums

  • A fixed set. You cannot add constants at run time. If the list of values comes from a database or config, use a regular class or a map instead.
  • No other superclass. The tutorial explains that all enums implicitly extend java.lang.Enum, and since a class can only extend one parent, an enum cannot extend anything else.
  • No public constructor. You can only use the constants that were declared.

Common mistakes

  • Storing ordinal() in a database or file. The ordinal is the position in the declaration. Insert a constant in the middle or reorder them, and every saved number now points at a different constant. Store the name, or give the enum an explicit field such as code and save that.
  • Forgetting the semicolon. If the enum body has fields, constructors or methods, the constant list must end with ;. Without it the compiler reports a syntax error at the first field or method.
  • Making the constructor public. It must be package-private or private. Writing public Planet(...) is a compile error.
  • Wrong case in valueOf. valueOf("monday") throws IllegalArgumentException for a constant declared as MONDAY. Normalize the input first, for example with toUpperCase(), if your data is not guaranteed to match.
  • Qualifying the name in a case label. In the classic switch form shown above, you write case MONDAY:, not case Day.MONDAY:.

As of November 2026, these rules apply to current Java versions, and the API pages cited in the sources below are for Java SE 21. Check the documentation for your own JDK if you rely on a newer or older release.

Frequently asked questions

What is an enum in Java?
An enum is a special type whose variables can only be one of a fixed set of predefined constants. You declare it with the enum keyword, for example public enum Day { MONDAY, TUESDAY }. Each constant is created automatically, and the type can also have fields, constructors and methods.
Can an enum have a constructor in Java?
Yes, but it must be package-private or private. The constructor runs automatically for each constant listed at the top of the enum body, using the arguments you write in parentheses after the constant name. You cannot call an enum constructor yourself.
What happens if valueOf() gets a name that does not exist?
It throws IllegalArgumentException. The name must match a declared constant exactly, and extra whitespace is not allowed. Passing null throws NullPointerException.
Can an enum extend a class in Java?
No. Every enum implicitly extends java.lang.Enum, and a Java class can only extend one parent class, so an enum cannot extend anything else.
Should I use ordinal() to store an enum?
Usually not. The Java documentation says most programmers have no use for ordinal(), which exists for data structures such as EnumSet and EnumMap. The ordinal changes if you reorder or insert constants, so store the name or an explicit field instead.

Sources