A Java enum is a special class that defines a fixed set of named constants, such as days of the week, order states or HTTP methods. Declare one with the enum keyword. Each constant is a singleton instance, so enums are type-safe, can be compared with ==, and work directly in switch expressions and in EnumMap and EnumSet.
Enums are more than labels: they can have fields, constructors, methods and even per-constant behaviour, and they can implement interfaces. They cannot extend another class, because every enum implicitly extends java.lang.Enum.
Constants are public static final by convention and are written in upper case. Use them like this:
Use == to compare enums; there is exactly one instance of each constant. Avoid relying on ordinal() for storage, because reordering constants changes it. Store the name() or an explicit code instead.
| Method | What it does |
|---|---|
values() | Returns a new array of all constants in declaration order |
valueOf(String) | Returns the constant with that exact name, or throws IllegalArgumentException |
name() / toString() | Constant name (toString() can be overridden) |
ordinal() | Zero-based position |
compareTo(E) | Compares by ordinal |
An enum constructor is implicitly private. Add data after the constants, separated by a semicolon.
Keep enum fields final so the constants stay immutable.
Each constant can override an abstract method, which replaces long if chains.
An enum can also implement an interface, which is the way to give a closed set of options a shared type that other code accepts.
Modern Java checks switch expressions over enums for exhaustiveness, so adding a constant produces a compile error where you forgot to handle it.
For collections keyed by an enum, use the specialised classes. They are compact and fast because they use arrays or bit sets internally.
A single-constant enum is a safe way to write a singleton, because the JVM guarantees one instance and it survives serialization and reflection attacks.
Enums also pair well with records and sealed types: use an enum for a closed set of simple constants, and a sealed interface with records when each case carries different data.
No. It already extends java.lang.Enum, and Java has single inheritance. It can implement any number of interfaces.
new?No. The constructor is private, so only the declared constants exist.
valueOf throws on unknown names and is case-sensitive. Wrap it in a method that catches IllegalArgumentException, or look the constant up in a Map built from values().
The constants are created once during class initialisation, which the JVM makes thread-safe. Mutable fields inside an enum are not automatically safe, so keep them final.
A Java enum defines a closed set of type-safe constants that can carry fields, methods and per-constant behaviour. Compare with ==, use exhaustive switch expressions, prefer EnumMap and EnumSet for enum keys, and do not persist ordinal().