Java Enum Classes: Enumerated Types with Fields and Methods
Java enums are full classes with a fixed set of instances. Learn to compare with ==, use name, valueOf, values, ordinal and compareTo, add fields, constructors and methods, write constant-specific behavior, switch over enums, and use EnumMap and EnumSet.
kvi5hnuCode Sprout team member8 min readOn this page
You met enumerated types in Part 3, together with switch expressions. Here's a typical one:
public enum Roast { LIGHT, MEDIUM, DARK, FRENCH }
That one-liner hides a lot. An enum declaration defines a class, and enums can have fields, constructors and methods, implement interfaces, and even give each constant its own behavior. This article covers all of it.
Referring to Enum Constants
Normally you qualify constants with the type name: Roast.LIGHT. The unqualified name works in three situations:
-
Inside the methods of the enum itself. Enums can have methods, as you'll see shortly.
-
In the
caselabels of aswitchwhose selector has the enum type:javaRoast s = . . .; String abbrev = switch (s) { case LIGHT -> "L"; case MEDIUM -> "M"; case DARK -> "D"; case FRENCH -> "F"; };A
switchexpression over an enum must be exhaustive. Since all four constants are covered, nodefaultis needed, and if someone adds a constant later, the compiler flags every switch that misses it. -
After a static import of all constants:
javaimport com.example.util.Roast; import static com.example.util.Roast.*; . . . Roast s = LIGHT;
An Enum Is a Class with a Fixed Set of Instances
The type defined by an enum declaration is a class. Roast has exactly four instances, created when the class is initialized, and it's impossible to construct new ones:
new Roast()→error: enum classes may not be instantiatedclass Espresso extends Roast→error: cannot inherit from final Roast/enum classes are not extensible

Since every value is unique, compare enum values with ==. You never need equals (which, for enums, does the same thing). == is also null-safe on either side and is checked at compile time: comparing a Roast with a DayOfWeek is an error.
Methods Inherited from Enum
Every enum type is a subclass of the abstract class java.lang.Enum (more precisely, Roast extends Enum<Roast>; the type parameter is used by compareTo, see the generics part). Useful inherited and generated methods:
| Method | Description |
|---|---|
String name() | The constant's name exactly as declared: Roast.LIGHT.name() → "LIGHT". name is final. |
String toString() | By default returns name(). You can override it, for example to return a display label. |
static Roast valueOf(String name) | The converse of name: Roast.valueOf("LIGHT") → Roast.LIGHT. Throws IllegalArgumentException: No enum constant Roast.HUGE for unknown names. |
static <T> T Enum.valueOf(Class<T> enumClass, String name) | The general form: Enum.valueOf(Roast.class, "LIGHT") |
static Roast[] values() | A new array of all constants in declaration order: [LIGHT, MEDIUM, DARK, FRENCH] |
int ordinal() | Zero-based position in the declaration: Roast.MEDIUM.ordinal() → 1 |
int compareTo(Roast other) | Negative, zero or positive, by declaration order |
Fields, Constructors and Methods
You can add constructors, methods and fields to an enum. The constructor runs once per constant, when the constants are created:
public enum Roast {
LIGHT("L"), MEDIUM("M"), DARK("D"), FRENCH("F");
private final String code;
Roast(String code) { this.code = code; } // automatically private
public String getCode() { return code; }
}
Each constant passes its arguments to the constructor in parentheses.
- When an enum has fields or methods, terminate the list of constants with a semicolon. (A trailing comma followed by a semicolon is also legal.)
- The constructor of an enum is always private. You can omit
private. Declaring itpublicorprotectedis a syntax error:modifier public not allowed here. - Make enum fields
final. Enum constants are shared, global singletons, and mutable state in them is a recipe for bugs.
Constant-Specific Behavior
You can even give individual constants their own method bodies:
public enum Roast {
LIGHT,
MEDIUM,
DARK,
FRENCH {
@Override
public String toString() { return "French roast"; }
};
}
That's not common. Here FRENCH is an instance of an anonymous subclass of Roast, the only kind of subclass an enum can have. The idiom becomes really useful with an abstract method that every constant implements:
enum Operation {
PLUS("+") {
public int apply(int a, int b) { return a + b; }
},
TIMES("*") {
public int apply(int a, int b) { return a * b; }
};
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
public abstract int apply(int a, int b);
@Override
public String toString() { return symbol; }
}
The compiler forces each constant to implement apply, so adding a new operation without its behavior is impossible. (With Java 21, a switch expression over this is often just as clear.)
Enums in the Library: EnumSet and EnumMap
The collections framework has specialized, very fast collections for enums:
EnumSetstores a set of constants as a bit vector:EnumSet.of(Roast.LIGHT, Roast.DARK),EnumSet.range(Roast.MEDIUM, Roast.FRENCH),EnumSet.allOf(Roast.class).EnumMapis a map keyed by enum constants, backed by an array and kept in declaration order:new EnumMap<Roast, Integer>(Roast.class).
Enums can also implement interfaces, and a single-constant enum (enum Registry { INSTANCE; ... }) is a simple, serialization-safe way to implement a singleton.
A Complete Program
The program reads a roast from the user, converts it with Enum.valueOf, and exercises the features above. (Here the input is dark.)
import java.util.*;
public class Solution {
public static void main(String[] args) {
var in = new Scanner(System.in);
System.out.print("Enter a roast: (LIGHT, MEDIUM, DARK, FRENCH) ");
String input = in.next().toUpperCase();
Roast roast = Enum.valueOf(Roast.class, input);
System.out.println("roast=" + roast);
System.out.println("code=" + roast.getCode());
if (roast == Roast.FRENCH) {
System.out.println("Bold choice: the darkest roast.");
}
System.out.println(Roast.valueOf("LIGHT").name() + " " + Roast.MEDIUM.ordinal()
+ " " + Arrays.toString(Roast.values()));
System.out.println(Roast.LIGHT.compareTo(Roast.DARK) < 0);
String advice = switch (roast) {
case LIGHT, MEDIUM -> "bright cup";
case DARK -> "full body";
case FRENCH -> "smoky";
};
System.out.println(advice + " " + roast.isStrong());
// constant-specific behavior
for (Operation op : Operation.values()) {
System.out.println(op + " " + op.apply(6, 3));
}
// EnumMap and EnumSet
var stock = new EnumMap<Roast, Integer>(Roast.class);
stock.put(Roast.DARK, 4);
stock.put(Roast.LIGHT, 10);
System.out.println(stock);
System.out.println(EnumSet.range(Roast.MEDIUM, Roast.FRENCH));
try {
Roast.valueOf("HUGE");
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
}
}
enum Roast {
LIGHT("L"), MEDIUM("M"), DARK("D"), FRENCH("F");
private final String code;
Roast(String code) { this.code = code; } // automatically private
public String getCode() { return code; }
public boolean isStrong() {
return switch (this) { // fine in a method, not in the constructor
case DARK, FRENCH -> true;
default -> false;
};
}
}
enum Operation {
PLUS("+") {
public int apply(int a, int b) { return a + b; }
},
TIMES("*") {
public int apply(int a, int b) { return a * b; }
};
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
public abstract int apply(int a, int b);
@Override
public String toString() { return symbol; }
}
Enter a roast: (LIGHT, MEDIUM, DARK, FRENCH) roast=DARK
code=D
LIGHT 1 [LIGHT, MEDIUM, DARK, FRENCH]
true
full body true
+ 9
* 18
{LIGHT=10, DARK=4}
[MEDIUM, DARK, FRENCH]
No enum constant Roast.HUGE
Note that the EnumMap prints in declaration order (LIGHT before DARK), not insertion order.
Common questions
How do I convert a string to an enum safely?
Roast.valueOf("DARK") throws IllegalArgumentException for unknown names, and NullPointerException for null. For user input, normalise first (s.strip().toUpperCase(Locale.ROOT)) and catch the exception, or search Roast.values() for a matching constant and return an Optional.
Can I add constants to an enum at runtime? No. The set of constants is fixed when the enum is compiled. If the values must come from a database or a configuration file, use a regular class (or a record) with a registry instead of an enum.
Can enums implement interfaces?
Yes, and this is a common way to make a set of constants extensible. For example, enum BasicOperation implements Operation { ... } lets other code define additional Operation implementations, while each enum still gives you its fixed constants.
Is values() expensive?
Each call returns a new copy of the constants array, so calling it in a hot loop creates garbage. Cache it in a private static final field, or iterate over EnumSet.allOf(Roast.class).
Why use EnumMap instead of HashMap with enum keys?
EnumMap stores values in an array indexed by ordinal. That makes it faster and more compact, and it iterates in declaration order. It also has no hashing overhead. Use it whenever all the keys are constants of one enum.
Summary
- An
enumdeclares a final class with a fixed set of instances. You can't create more or subclass it, so compare values with==. - Unqualified constant names work inside the enum, in
switchcases, and afterimport static. - Every enum extends
Enum:name(),toString(),valueOf,values(),ordinal(),compareTo. Don't persist ordinals. - Enums can have fields, methods and (always private) constructors. End the constant list with a semicolon when anything follows.
- Constants can override methods individually, and an abstract method forces each constant to implement it.
- Use
EnumSetandEnumMapfor sets and maps of enum constants.switchexpressions over enums must be exhaustive.
Practice Questions
Why is it safe to compare enum values with == but not strings?
Each enum constant is a single, unique object; no other instance can ever be created. So == is equivalent to equals. Different String objects can have the same content, so == on strings can fail.
What do Roast.DARK.name(), Roast.DARK.ordinal() and Roast.valueOf("Dark") return for the Roast enum above?
"DARK", 2, and an IllegalArgumentException: valueOf is case-sensitive, and there's no constant named Dark.
Write an enum Planet with constants MERCURY(3.303e+23, 2.4397e6) and EARTH(5.976e+24, 6.37814e6) storing mass and radius, plus a method surfaceGravity() = G * mass / radius².
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
EARTH(5.976e+24, 6.37814e6);
private static final double G = 6.67300E-11;
private final double mass, radius;
Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
double surfaceGravity() { return G * mass / (radius * radius); }
}
Why can't an enum's constructor be public?
Callers could then create additional instances, breaking the guarantee that the declared constants are the only instances. Enum constructors are always private and run only for the declared constants.
A database column stores Roast.ordinal(). A colleague adds MEDIUM_DARK between MEDIUM and DARK. What goes wrong, and what's the fix?
Every stored ordinal of 2 or higher now maps to the wrong constant (old DARK, ordinal 2, would read as MEDIUM_DARK). Store name() or a dedicated, stable code field instead.
Previous: Java Abstract Classes and Abstract Methods
Next: Java Sealed Classes and Interfaces: Controlling Inheritance
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.