Java Enums: Switches, Fields, Constructors, Serialization
Explore Java enums, exhaustive switch expressions, per-constant fields, constructor rules, custom ordering, and serialization without fragile ordinals.
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
defaultare 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 keepname()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
}
-
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 -
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. -
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 -
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.Enumand 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; avoidordinal()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
publicorprotected; 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
Further Reading
- Java Variables and Constants - Static final constants and variable declaration
- Java Switch Expressions - Switch expression syntax and exhaustiveness
- Java Interfaces - Implementing interfaces with enum types
- Java SE 27 JLS §8.9.2 - Enum declaration and constructor rules
- Java SE 27 Enum API - Enum ordering and serialization contract
- Enum Patterns - Oracle Tutorial - Enum declarations and examples
- Effective Java - Item 34 - Use enums instead of constants (Joshua Bloch)
- Enum Implementation - OpenJDK - Source code for
java.lang.Enum - Java Enum Tricks - Additional enum examples
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.
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 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.