Java Enums: Switches, Fields, Constructors, Serialization

Explore Java enums, exhaustive switch expressions, per-constant fields, constructor rules, custom ordering, and serialization without fragile ordinals.

published: reading time: 19 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Explore Java enums, exhaustive switch expressions, per-constant fields, constructor rules, custom ordering, and serialization without fragile ordinals.

Java Enums

Java enums define fixed sets of named constants. They provide a type-safe alternative to string or integer flags and can hold data or methods alongside each constant.

Introduction

An enum implicitly extends java.lang.Enum and has no instances beyond its constants. It can declare fields and methods, implement interfaces, and provide constant-specific behavior. Enum constructors cannot be public or protected; under JLS §8.9.2, a constructor declaration with no access modifier is private, as is the default constructor when none is declared.

An enum parameter accepts only values of that enum type. Use enums for a closed set that changes with the application; use configuration or data-backed values when the set must change independently.

ordinal() is the constant’s zero-based position in its declaration. Reordering or inserting constants changes that position, so do not use it as a persisted or business identifier. name() returns the declared identifier; renaming a constant changes that value too. If a database or API needs a long-lived code, define one explicitly.

When to Use / When Not to Use

Use enums when:

  • You have a fixed, closed set of related values
  • You need type safety to prevent invalid values
  • Values are used as map keys or in switch statements
  • You want to attach behavior or data to constants

Consider alternatives when:

  • You need open-ended sets (use classes or interfaces)
  • Values come from external systems (use configuration)
  • You need dynamic creation of types at runtime
  • The set changes frequently (database-backed lookup)

Switches with Enum Values

A traditional switch statement over an enum does not have to cover every constant. If no label matches a non-null value, the statement completes normally without executing a case. A switch expression is different: it must be exhaustive. Listing every enum constant without default lets the compiler check completeness when the code is recompiled after the enum changes.

enum Status {
    PENDING,
    APPROVED,
    REJECTED
}

public class EnumSwitchDemo {
    public static void main(String[] args) {
        printTraditional(Status.REJECTED);
        System.out.println(label(Status.REJECTED));
    }

    static void printTraditional(Status status) {
        switch (status) {
            case PENDING:
                System.out.println("waiting");
                break;
            case APPROVED:
                System.out.println("approved");
                break;
        }
        System.out.println("statement continued");
    }

    static String label(Status status) {
        return switch (status) {
            case PENDING -> "waiting";
            case APPROVED -> "approved";
            case REJECTED -> "rejected";
        };
    }

    static String labelWithDefault(Status status) {
        return switch (status) {
            case PENDING -> "waiting";
            case APPROVED -> "approved";
            default -> "other";
        };
    }
}

For REJECTED, the traditional statement skips both cases and prints statement continued. The expression names each constant and needs no default. If a new enum constant is added, that expression will fail exhaustiveness checking when recompiled. A default makes it exhaustive without naming all constants, so a new constant will be accepted by the fallback instead of prompting a compile-time update.

The example prints:

statement continued
rejected

Switch expressions became a permanent feature in Java SE 14. Pattern matching for switch is separate syntax that became permanent in Java SE 21. See the Java SE 14 language changes, Java SE 21 language changes, Oracle’s pattern matching for switch guide, and the Java SE 27 JLS §14.11 switch rules.

Enum Architecture

graph TD
    A["enum Status"] --> B["PENDING"]
    A --> C["APPROVED"]
    A --> D["REJECTED"]

    B --> E["ordinal: 0"]
    C --> F["ordinal: 1"]
    D --> G["ordinal: 2"]

    E -.-> H["name(): \"PENDING\""]
    F -.-> I["name(): \"APPROVED\""]
    G -.-> J["name(): \"REJECTED\""]

    K["Enum Class<br/>extends java.lang.Enum"] --> A

    style A stroke:#ff00ff,color:#ff00ff
    style B stroke:#00fff9,color:#00fff9
    style C stroke:#00fff9,color:#00fff9
    style D stroke:#00fff9,color:#00fff9
    style K stroke:#00ff00,color:#00ff00

Production Failure Scenarios

Scenario Cause Mitigation
Traditional switch misses a value No case label matches; the statement can do nothing Use an exhaustive expression when computing a result
Default masks a new constant A fallback accepts constants not listed in the expression Omit default when compile-time enum completeness is useful
Ordinal dependence Declaration order changes the ordinal Use an explicit code or name() when it is part of the data contract
Custom enum serialization Enum serialization has a fixed representation Do not rely on readResolve to change it
Mutable enum fields Every caller observes the same constant instance and its shared fields Prefer private final metadata; protect mutable state with normal concurrency controls
enum Status {
    PENDING,
    APPROVED,
    REJECTED;

    Status next() {
        return switch (this) {
            case PENDING -> APPROVED;
            case APPROVED -> REJECTED;
            case REJECTED -> throw new IllegalStateException("No next status");
        };
    }
}

// Avoid using ordinal as a business value: its value follows declaration order.
Status next = Status.PENDING.next();

Trade-off Table

Feature Enum Static Final Constants Class with Private Constructor
Type safety Yes No (int can be any value) Limited
Exhaustive enum switch expression Yes (without default) No No
Can have methods Yes No Yes
Can implement interfaces Yes No Yes
Switch support Yes Yes (primitive) No
Grouping Natural Scattered Manual
Serialization Special handling; fixed form Manual Manual

Implementation Snippets

Basic Enum Definition

Use plain constants when each value has no associated data or behavior. Unlike strings, the enum type restricts variables to the declared constants. A switch expression over an enum can also be checked for completeness when it lists every constant and has no default; traditional switch statements do not get that check.

An enum implicitly extends java.lang.Enum. The compiler declares a field for each constant and generates values() and valueOf(String) methods. name() returns the identifier exactly as declared. Switch implementation strategy is a compiler detail; do not depend on a particular lookup strategy.

public enum Status {
    PENDING,
    APPROVED,
    REJECTED
}

// Using the enum
Status current = Status.PENDING;
String message = switch (current) {
    case PENDING -> "Waiting";
    case APPROVED -> "Go ahead";
    case REJECTED -> "No go";
};
System.out.println(message);

// Enum methods (auto-generated by compiler)
Status.values();      // All values: [PENDING, APPROVED, REJECTED]
Status.valueOf("PENDING");  // Parse string to enum
Status s = Enum.valueOf(Status.class, "PENDING"); // Equivalent

// ordinal() - position in declaration order (0-based)
Status.PENDING.ordinal();  // 0
Status.APPROVED.ordinal(); // 1

Enum with Custom Fields and Methods

Pass associated data such as an HTTP code to the enum constructor, then expose only the accessors callers need. Each constant is created once and shared, so its instance fields are shared too. private final fields holding immutable values, as below, keep this metadata fixed; mutable enum fields are shared state and are not automatically thread-safe. Enum constants have unique identity, so == is appropriate for comparing them.

public enum HttpStatus {
    OK(200, "OK"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_ERROR(500, "Internal Server Error"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable");

    // Custom fields
    private final int code;
    private final String description;

    // No modifier; enum constructors cannot be public or protected.
    HttpStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    // Custom methods
    public int getCode() { return code; }
    public String getDescription() { return description; }

    public boolean isSuccess() {
        return code >= 200 && code < 300;
    }

    public boolean isError() {
        return code >= 400;
    }

    // Static lookup by code
    public static HttpStatus fromCode(int code) {
        for (HttpStatus status : values()) {
            if (status.code == code) {
                return status;
            }
        }
        throw new IllegalArgumentException("Unknown HTTP code: " + code);
    }
}

// Usage
HttpStatus status = HttpStatus.fromCode(404);
System.out.println(status.getDescription()); // "Not Found"
System.out.println(status.isError());        // true

Enum with Behavior: State Pattern

An enum can declare an abstract method and have each constant implement it. This can fit a small state machine when behavior belongs to the state itself. Calls such as state.submit(order) use normal method dispatch; a larger state machine may be clearer as separate classes or a transition table.

public enum OrderState {
    // Each constant implements its behavior differently
    DRAFT {
        @Override
        public void submit(Order order) {
            order.setState(SUBMITTED);
            order.setSubmittedAt(Instant.now());
        }
    },
    SUBMITTED {
        @Override
        public void submit(Order order) {
            throw new IllegalStateException("Order already submitted");
        }

        @Override
        public void process(Order order) {
            order.setState(PROCESSING);
        }
    },
    PROCESSING {
        @Override
        public void complete(Order order) {
            order.setState(COMPLETED);
        }
    },
    COMPLETED {
        @Override
        public void cancel(Order order) {
            throw new IllegalStateException("Cannot cancel completed order");
        }
    };

    // Abstract method - each state implements its own behavior
    public abstract void submit(Order order);
    public abstract void process(Order order);
    public abstract void complete(Order order);
    public abstract void cancel(Order order);
}

// Usage with state pattern
public class Order {
    private OrderState state = OrderState.DRAFT;

    public void submit() {
        state.submit(this);
    }

    public void cancel() {
        state.cancel(this);
    }
}

Enum Implementing Interface

Enums can implement interfaces but cannot extend another class because each enum already extends java.lang.Enum. An interface such as Describable lets callers use an enum through a shared contract without depending on the enum type.

public interface Describable {
    String getDescription();
    String getCategory();
}

public enum Priority implements Describable {
    LOW("Background tasks", "batch"),
    MEDIUM("User-facing operations", "interactive"),
    HIGH("Time-sensitive operations", "realtime"),
    CRITICAL("System failures", "alert");

    private final String description;
    private final String category;

    Priority(String description, String category) {
        this.description = description;
        this.category = category;
    }

    @Override
    public String getDescription() { return description; }

    @Override
    public String getCategory() { return category; }
}

// Use with interface
List<Describable> items = List.of(Priority.HIGH, Priority.LOW);
for (Describable item : items) {
    System.out.println(item.getCategory() + ": " + item.getDescription());
}

Observability Checklist

  • Track enum value distribution in production (which values are most common)
  • Review traditional switch statements when adding enum values; expressions without default are checked for exhaustiveness
  • Log enum transitions in state machines
  • Alert on unexpected enum values in deserialized data
  • Measure performance of valueOf() for parsing
// Observability for enums
public class EnumMetrics {
    public static void trackStatusUsage(Status status) {
        metrics.increment("status." + status.name());
    }

    public static void trackTransition(Status from, Status to) {
        Logger.info("Status transition: {} -> {}", from, to);
        metrics.record("transition." + from.name() + ".to." + to.name());
    }
}

Common Pitfalls / Anti-Patterns

  • Input validation: Always use enum’s valueOf() or fromCode() inside try-catch for untrusted input
  • Serialization: Java preserves enum constant identity; its serialized representation cannot be customized
  • Database storage: Avoid ordinal(); use an explicit application code or keep name() stable as part of the data contract
  • Configuration validation: Enums provide natural validation boundary
// Security: safe parsing of untrusted input
public static Status parseStatus(String input) {
    if (input == null || input.isBlank()) {
        throw new IllegalArgumentException("Status cannot be empty");
    }
    try {
        return Status.valueOf(input.toUpperCase().trim());
    } catch (IllegalArgumentException e) {
        throw new SecurityException("Invalid status: " + input);
    }
}

// Safe database storage
public void saveOrder(int orderId, Status status) {
    // Store name, not ordinal - ordinal can change on code reorder
    stmt.setString(2, status.name()); // "APPROVED", "REJECTED", etc.
}

public Status loadStatus(String name) {
    return Status.valueOf(name); // Parse from stored name
}
  1. Using ordinal() for lookup or comparison

    // BAD - ordinal can change if enum constants are reordered
    int index = status.ordinal(); // Fragile
    
    // GOOD - use name() or custom field
    String name = status.name(); // Stable
    int code = status.getCode();  // If you have a custom field
  2. Adding new enum value without updating switch

    // A traditional colon-label switch statement may omit an enum constant.
    switch (status) {
        case PENDING:
            handlePending();
            break;
        case APPROVED:
            handleApproved();
            break;
        // If status is REJECTED, neither case runs.
    }
    
    // For a result, use a switch expression without default
    // and list every enum constant. See the section above.
  3. Trying to add enum constants at runtime

    // An enum's constant set is fixed when the type is declared. You cannot:
    // - Add new constants after class is loaded
    // - Remove existing constants
    // - Change behavior of existing constants
    // This is by design - enums represent fixed sets
  4. Confusing enum with class that could be enum

    // BAD - using class when enum is appropriate
    public class Status {
        public static final String PENDING = "PENDING";
        public static final String APPROVED = "APPROVED";
        // No type safety! Could pass any string
    }
    
    // GOOD - actual enum
    public enum Status { PENDING, APPROVED }
    // Only Status values can be used, compiler enforces this

Quick Recap Checklist

  • Enums extend java.lang.Enum and can declare fields, methods, and constructors
  • Enum constants are implicitly public static final
  • Use name() for the declared identifier only when that name is part of the data contract; avoid ordinal() for persisted values
  • valueOf() parses string to enum (throws IllegalArgumentException for invalid)
  • values() returns all constants in declaration order
  • Each constant can override behavior (abstract methods)
  • Enums can implement interfaces but cannot extend classes
  • Enum constructors cannot be public or protected; a no-modifier constructor is private under JLS §8.9.2
  • Use an explicit code or a deliberately stable name for persisted values, not ordinal()

Interview Questions

1. How does Java implement enums internally?
An enum declaration defines a restricted class that implicitly extends `java.lang.Enum`. The compiler creates one field and one instance for each constant, and supplies `values()` and `valueOf(String)`. An enum with no constant-specific class bodies is implicitly final; one with such bodies is implicitly sealed. Code does not instantiate enum constants with `new`.
2. Can enums have abstract methods?
Yes. Declare an abstract method in the enum and implement it in each constant's class body. This works when each constant needs distinct behavior, such as a state transition rule.
3. When should you use ordinal() versus custom fields?
Avoid `ordinal()` for business logic or persisted data because reordering or inserting constants changes the value. Use an explicit field for application codes. Use `name()` only when the declared name itself is part of the data contract.
4. Can enum constants have different behavior?
Yes. A constant-specific class body can override a concrete enum method. Calling that method on a constant dispatches to its implementation, while the caller still works with the enum type.
5. How do you safely parse user input to an enum value?
Call `Enum.valueOf(EnumType.class, input)` and handle `IllegalArgumentException` for an unknown name. Trim or normalize the input only if that matches the API's input rules; `valueOf()` itself requires an exact constant name.
6. Can enums implement interfaces? Can they extend classes?
Enums can implement interfaces, but an enum declaration cannot extend another class. Its direct superclass is `java.lang.Enum`, so there is no second superclass slot. An enum can implement multiple interfaces.
7. How would you iterate over all enum values?
Use the compiler-generated `values()` method to get the constants in declaration order. For a set, `EnumSet.allOf(Status.class)` is specialized for enum types and also iterates in declaration order.
8. What is the difference between ordinal() and name()?
`ordinal()` returns the constant's zero-based declaration position, which changes if constants are reordered or inserted. `name()` returns the declared identifier and is used by `valueOf()`; renaming the constant changes that value. For persisted data, use an explicit code or treat the name as a versioned contract.
9. How do enums work with switch statements?
A traditional enum `switch` statement may omit constants and then do nothing when no label matches. A `switch` expression must be exhaustive. Switch expressions became permanent in Java SE 14; pattern matching for `switch` became permanent in Java SE 21. See the switch examples above.
10. Can enum constants have multiple related values?
Yes. Pass values to the enum constructor and store them in fields. `final` fields containing immutable values keep that data fixed. Mutable fields are shared by all callers of the constant and need ordinary concurrency protection.
11. How does Java handle enum serialization?
Java serialization handles enum constants specially and preserves their identity. The serialized representation cannot be customized, and `readResolve()` does not provide a way to change it. Avoid `ordinal()` in any persisted format; use a deliberate application code if names may change.
12. When is a switch expression clearer than constant-specific behavior?
Use a switch expression when the cases are short and the result or action belongs in one place. Put the method on each constant when the behavior is distinct and callers should invoke it without branching.
13. How do enums handle null values in databases?
For stored values, map an explicit application code to the enum when names may change. Storing `name()` makes the identifier part of the data contract; storing `ordinal()` is fragile because declaration order can change. When reading, handle unknown values and nullable columns explicitly.
14. What is the performance characteristic of enum lookup?
`Enum.valueOf()` looks up a constant by name, but the API does not promise a complexity bound. `EnumSet` and `EnumMap` are specialized collection types for enum values and keys. `values()` returns an array of the constants; avoid calling it repeatedly in a hot loop if you can reuse the result.
15. How do enums interact with Java's type system?
Enums can implement interfaces and participate in polymorphism, but an enum declaration cannot declare type parameters. An enum can implement a generic interface with fixed type arguments or declare a generic method. Enum arrays are typed, so a `Status[]` cannot hold values of another enum type.
16. Can you use enums in TreeMap or TreeSet?
Enum constants implement `Comparable` and their final `compareTo()` method orders them by declaration. You cannot override it. For another order, pass a `Comparator` to a sort operation, `TreeSet`, or `TreeMap`.
17. How do you add data or behavior to an enum without breaking existing code?
Adding a new abstract enum method requires every constant to implement it. Adding a constant may require updating exhaustive switch expressions; a `default` can hide that omission. If enum names or values are persisted, plan changes against that data contract instead of relying on declaration order.
18. What is the relationship between enums and the Java Language Specification?
JLS §8.9 defines enum declarations as restricted classes that implicitly extend `java.lang.Enum`. Enum constructors cannot be `public` or `protected`; a declared constructor without an access modifier is private, and the default constructor is also private. An enum has no instances beyond its constants. Depending on whether constants have class bodies, an enum is implicitly final or sealed.
19. How does autoboxing interact with enum-backed code?
`ordinal()` returns an `int`, while `name()` returns a `String`; neither call boxes a value. An enum used as a collection element or map key is already a reference, so it needs no boxing. Boxing can occur if you pass the ordinal to an API that expects `Integer`.
20. How do you write a test for enum-based behavior?
Test each constant's behavior and the operations that use it. Include invalid transitions for state enums, null or unknown values for parsing, and each branch of an exhaustive switch expression. Parameterized tests can exercise the full constant set.

Further Reading

Conclusion

Java enums represent fixed sets of named constants. They can hold fields, define methods, and implement interfaces. Their constructors cannot be public or protected; under JLS §8.9.2, a declared constructor with no access modifier is private, and an implicitly declared default constructor is private too.

Use name() only when the declared identifier is part of the persisted contract; renaming a constant changes it. Do not use ordinal() as a database or business identifier. A switch expression that lists every enum constant without default is checked for exhaustiveness; a traditional enum switch statement can still omit a case. Enum constants are shared instances, but mutable fields are shared mutable state and are not inherently thread-safe. Java serialization preserves enum identity, and its serialized representation cannot be customized with readResolve().

For a comparison with static final constants, see Java Variables and Constants. The Java Switch Expressions guide covers the switch syntax in more detail.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals