Enum in Java: Examples, Methods, and Best Practices

How-to basics · Updated November 22, 2026

A Java enum is a type whose values are a fixed set of named constants. For example, declare enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }, then use a value as Day.MONDAY instead of an arbitrary string or number.

A Basic Java Enum Example

This small example defines the possible states of a delivery and uses one of them in a variable:

enum DeliveryStatus {
    PENDING,
    IN_TRANSIT,
    DELIVERED,
    CANCELLED
}

class DeliveryExample {
    public static void main(String[] args) {
        DeliveryStatus status = DeliveryStatus.IN_TRANSIT;

        if (status == DeliveryStatus.IN_TRANSIT) {
            System.out.println("The delivery is on its way.");
        }
    }
}

Each constant is an instance of DeliveryStatus. The compiler can therefore catch mistakes such as assigning an unrelated value to status. A string-based version might accept misspellings such as "IN_TRANSIT" or "IN-TRANSIT" until runtime; the enum version makes the permitted choices explicit in the type.

What an Enum Means in Java

An enum (short for enumeration) models a category with a known, limited set of instances. Common examples include directions, order statuses, seasons, and command types. If an application has a value that should be one of a defined set, an enum is often clearer and safer than a collection of string literals or integer codes.

In Java, an enum is more than a list of labels. It is a special kind of class, and each declared constant is a singleton instance of that enum type. An enum implicitly extends java.lang.Enum, so it cannot extend another class. It can, however, implement one or more interfaces. Enum constants are conventionally written in uppercase with underscores between words, although that naming style is a convention rather than a language requirement.

The type boundary is useful: a method that accepts DeliveryStatus communicates which values are valid, and callers cannot pass an unrelated string without converting it. If a new status is added, the compiler can also help locate code that needs to account for it.

Adding Fields and Constructors

Enum constants can carry data. Put a constructor argument after each constant, declare a field, and provide a method to read it. This is useful when each option has a stable property, such as a display label, code, or numeric setting.

enum Priority {
    LOW(10),
    NORMAL(20),
    HIGH(30);

    private final int level;

    Priority(int level) {
        this.level = level;
    }

    public int getLevel() {
        return level;
    }
}

Here, Priority.HIGH.getLevel() returns 30. The constructor is private in effect: enum constructors cannot be public or protected, and callers cannot create additional instances with new. A constructor can accept multiple arguments, and each constant must supply the required arguments.

Prefer immutable fields, often declared private final, when the value is part of the constant’s definition. Avoid making enum state mutable just to store information that changes independently for each user or request. Since enum constants are shared instances, mutable fields can create surprising shared state, especially in concurrent programs.

Built-In Enum Methods

Java provides useful methods for working with enum constants. For an enum named Priority, the compiler supplies values(), which returns the constants in declaration order, and valueOf(String), which finds a constant by its exact declared name.

for (Priority priority : Priority.values()) {
    System.out.println(priority);
}

Priority selected = Priority.valueOf("HIGH");

valueOf is case-sensitive: "HIGH" matches, while "high" does not. An unknown name causes IllegalArgumentException; passing null causes NullPointerException. If a name comes from user input or a file, validate or handle these exceptions rather than assuming it is valid.

Every enum also has name(), which returns the exact declared identifier, and toString(), whose default result is the same but which can be overridden for presentation. ordinal() returns a zero-based position in the declaration. It can be handy for limited internal ordering tasks, but it is not a durable identifier: inserting or reordering constants changes ordinal values. Do not store ordinals as database codes or send them as long-lived protocol values.

Using Enums in If Statements and Switches

Compare enum values with ==. Because each constant is a single instance, identity comparison is appropriate and avoids concerns such as calling equals on a possibly null variable. A switch statement is another readable way to handle several alternatives:

switch (status) {
    case PENDING:
        System.out.println("Waiting to ship.");
        break;
    case IN_TRANSIT:
        System.out.println("On the way.");
        break;
    case DELIVERED:
        System.out.println("Arrived.");
        break;
    case CANCELLED:
        System.out.println("Delivery stopped.");
        break;
    default:
        System.out.println("Unrecognized status.");
}

The case labels use the constant names without repeating DeliveryStatus.. The traditional switch statement shown here works on older Java versions that support enums. The break statements prevent execution from falling through into the next case. Keep a default when a fallback is useful, particularly if values may come from an evolving system. Newer Java releases also support switch expressions, but their syntax and exhaustiveness rules differ from this classic statement.

Enums with Collections

When a collection’s elements are all values of one enum type, Java’s EnumSet is a purpose-built option. It represents a set of constants compactly and provides familiar set operations.

import java.util.EnumSet;

EnumSet<Priority> urgent = EnumSet.of(Priority.NORMAL, Priority.HIGH);
urgent.add(Priority.LOW);

if (urgent.contains(Priority.HIGH)) {
    System.out.println("High priority is included.");
}

EnumMap is a map whose keys come from a single enum type. For instance, a Map<Day, String> can associate a schedule entry with each day. EnumMap can make the intent clear and is designed for enum keys. Choose these collections when their constraints fit; use general-purpose collections when keys or elements need to include other types.

When to Choose an Enum or an Alternative

Choose an enum when the set of choices is controlled by the application and changing it requires a code change. It works well for internal states, fixed options, and values used in method parameters or return types. The compiler can help enforce the allowed choices, and an enum can keep related behavior and data together.

A string or a configurable lookup may be more appropriate when values are created by administrators, come from external systems, or must be added without recompiling the application. For example, a plug-in system with user-defined categories should not assume that every category can be declared as a Java enum constant. A string is more flexible but needs validation, and it is easier for inconsistent spelling or casing to creep in.

Integer constants are sometimes found in older code, but they do not provide the same type safety: an integer variable can hold values that have no meaning for the intended category. Replacing a public integer constant with an enum may also affect compatibility with existing callers, serialized data, or APIs, so treat it as a design and migration decision rather than a purely cosmetic change.

Common Enum Mistakes and Design Tips

  • Persisting ordinals: Do not use ordinal() as a permanent database value or wire-format code. Assign an explicit stable code in a field if a durable mapping is needed, and define how that mapping will be maintained.
  • Assuming external text is valid: valueOf requires an exact constant name. If input may vary in case or spelling, normalize it deliberately and report invalid values clearly rather than allowing an unexpected exception to escape.
  • Using display text as an identifier: A user-facing label may need translation or wording changes. Keep stable identifiers separate from display labels, which can be supplied through methods or a localization system.
  • Overusing enums for changing data: A long or frequently edited list of values may belong in configuration or storage rather than source code. Enums are best when the alternatives are genuinely part of the program’s fixed model.
  • Forgetting null: Enum variables are reference types and can be null. A switch on a null enum reference throws NullPointerException; initialize values sensibly or check inputs where null is possible.

An enum can also declare methods, implement interfaces, and override behavior for individual constants when that makes the design simpler. Avoid turning a small fixed set into an elaborate framework without a real need. The central benefit is a named, type-safe set of alternatives; keep the implementation focused on that job.

Frequently Asked Questions

Can an enum have methods in Java?

Yes. An enum can define fields, constructors, and instance or static methods. For example, it can expose a display label or calculate a property associated with each constant.

Can a Java enum extend a class?

No. An enum already extends java.lang.Enum, so it cannot extend another class. It can implement interfaces, which is the usual way to give enum types a shared contract.

Why use an enum instead of a String?

An enum restricts a variable to declared choices and lets the compiler check many mistakes. A string is more flexible for dynamic or externally defined values, but it requires careful validation and consistent naming.

Can enum constants have different behavior?

Yes. Constants can provide constant-specific class bodies that override an abstract method declared by the enum. Use this when each option has meaningfully different behavior; for simple differences, a field may be easier to understand.

Is it safe to save an enum’s ordinal?

Usually not for data that must remain valid across versions. Ordinals depend on declaration order and can change when constants are inserted or rearranged. Store an explicit stable code or name instead, with a plan for handling renamed or retired values.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.