Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An enum (enumeration) in Java is a specialized class type used to define a collection of unchangeable, compile-time constants. Under the hood, every enum implicitly extends the java.lang.Enum abstract class. Because Java does not support multiple inheritance for classes, an enum cannot extend another class, though it can implement multiple interfaces.

Basic Syntax

The simplest form of an enum is a comma-separated list of identifiers. By convention, enum constants are written in uppercase because they are implicitly public static final.
public enum ThreadState {
    NEW, RUNNABLE, BLOCKED, WAITING, TERMINATED
}

Internal Mechanics

When the Java compiler processes an enum, it translates it into a class. According to the Java Language Specification (JLS §8.9), an enum declaration is implicitly final unless it contains at least one enum constant with a class body, in which case it is implicitly abstract. Each declared constant becomes a static instance of that class. Conceptually, the compiler generates code similar to the following for a standard, implicitly final enum:
// Conceptual representation of compiled ThreadState enum
public final class ThreadState extends java.lang.Enum<ThreadState> {
    public static final ThreadState NEW = new ThreadState("NEW", 0);
    public static final ThreadState RUNNABLE = new ThreadState("RUNNABLE", 1);
    // ...
    
    private ThreadState(String name, int ordinal) {
        super(name, ordinal);
    }
}

Fields, Constructors, and Methods

Because enums are fully-fledged classes, they can encapsulate state and behavior. You can define instance fields, methods, and constructors within an enum. Enum constructors are strictly private. According to the Java Language Specification, if no access modifier is provided, the constructor is implicitly private. It is a compile-time error to use any access modifier other than private. The JVM invokes the constructor automatically during class initialization (when the static <clinit> block is executed), not during class loading. You cannot instantiate an enum using the new keyword.
public enum HttpResponse {
    OK(200, "Success"),
    NOT_FOUND(404, "Resource not found"),
    INTERNAL_ERROR(500, "Server failure");

    private final int statusCode;
    private final String message;

    // Implicitly private constructor
    HttpResponse(int statusCode, String message) {
        this.statusCode = statusCode;
        this.message = message;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getMessage() {
        return message;
    }
}

Constant-Specific Class Bodies

Enums support polymorphism at the constant level. You can declare an abstract method in the enum type and provide a concrete implementation for each constant. The compiler handles this by creating anonymous inner classes for each constant. Because this enum contains constants with class bodies, the compiler implicitly marks the ArithmeticOperation enum class as abstract rather than final.
public enum ArithmeticOperation {
    ADD {
        @Override
        public double execute(double x, double y) { return x + y; }
    },
    SUBTRACT {
        @Override
        public double execute(double x, double y) { return x - y; }
    };

    public abstract double execute(double x, double y);
}

Switch Statements and Expressions

Java provides native support for enums in switch constructs. The compiler infers the enum type, allowing the use of unqualified constant names directly in the case labels. This applies to both traditional switch statements and modern switch expressions.
ThreadState state = ThreadState.NEW;

// Switch expression
String description = switch (state) {
    case NEW -> "Thread is created but not started";
    case RUNNABLE -> "Thread is executing";
    case BLOCKED, WAITING -> "Thread is suspended";
    case TERMINATED -> "Thread has finished execution";
};

Specialized Collections: EnumSet and EnumMap

The java.util package provides highly optimized collection implementations specifically designed for enum types, avoiding the overhead of standard collections:
  • EnumSet: A Set implementation represented internally as a bit-vector. It is extremely compact and efficient, allowing bulk operations (like union or intersection) to execute using bitwise arithmetic.
  • EnumMap: A Map implementation where all keys must come from a single enum type. It is represented internally as an array, providing constant-time performance for lookups and insertions without the hashing overhead of a HashMap.
// EnumSet syntax
EnumSet<ThreadState> activeStates = EnumSet.of(ThreadState.NEW, ThreadState.RUNNABLE);

// EnumMap syntax
EnumMap<ThreadState, String> stateDescriptions = new EnumMap<>(ThreadState.class);
stateDescriptions.put(ThreadState.NEW, "Starting up");

Built-in Methods

The Java compiler and the java.lang.Enum base class provide several inherent methods to all enums:
  • values(): A static method injected by the compiler that returns an array containing all the constants of the enum in the order they are declared.
  • valueOf(String name): A static method injected by the compiler that returns the enum constant matching the exact string provided. Throws an IllegalArgumentException if no match is found.
  • name(): A final method that returns the exact identifier of the enum constant as a string.
  • ordinal(): A final method that returns the zero-based integer position of the constant in the enum declaration.

JVM Guarantees

  • Serialization: Enums handle serialization natively. The JVM guarantees that deserialized enum constants yield the exact same instance as the one residing in memory, preventing duplicate instances.
  • Thread Safety: The instantiation of enum constants during class initialization is guaranteed to be thread-safe by the JVM.
  • Comparison: Because the JVM ensures only one instance of each enum constant exists, they can be safely compared using the == operator instead of the .equals() method.
Master Java with Deep Grasping Methodology!Learn More