Java enums define a fixed set of named instances, such as shipping speeds or workflow states. An enum can store fields, run constructors and provide methods. Constructor arguments attach useful data to each constant without allowing callers to create extra enum values.
Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.
A closed set of values
An enum defines a fixed set of named instances. It is suitable for a small closed set of states, categories or modes.
Each enum constant is an instance of the enum type, created during class initialization. A constant can pass arguments to the enum constructor, which initializes fields for that instance. Constructors are private in effect and cannot be public or protected. Code outside the enum cannot construct a new value with new, so the declared constants remain the permitted set.
Fields on enum constants
Enum constants can pass arguments to constructors and hold fields. Each constant is an object of the enum type rather than an arbitrary integer code.
Give each constant a meaningful stable identity, then store descriptive attributes in explicit fields. A delivery speed can hold a number of days, while a status can expose whether it is terminal. final fields make those attributes harder to accidentally reassign. Avoid mutable per-constant state unless shared singleton-like behavior is genuinely intended: every use of a constant refers to the same instance.
Enum construction and exact name lookup
Enum constructors are not public; callers use the declared constants instead of constructing new enum instances.
values returns the constants in declaration order, and valueOf requires an exact declared name. Unknown names produce IllegalArgumentException; null produces NullPointerException. Normalize external text only when the application's input rules permit it. A human-readable label is separate from the constant's programmatic name and should not silently replace a documented persistence identifier.
Names, values and ordinals
values returns the constants in declaration order, while valueOf matches an exact constant name. Avoid storing ordinal as a durable identifier because changing declaration order changes its value.
ordinal gives a declaration position beginning at zero. It can change when constants are inserted or reordered, so do not use it as a durable database code. Prefer explicit identifiers and conversion rules. Enums work naturally with switch, EnumSet and EnumMap, which can express constrained choices more clearly than unrelated strings that accept misspellings.
Running the examples
Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.
How StallEnumValues produces its output
The constant's constructor argument initializes its associated field once. Calling the accessor later reads that value from the enum instance. Iterating values follows declaration order, not numeric sorting of the attached data. This allows a constant to have a stable descriptive name while presenting useful attributes.
How DeliverySpeeds produces its output
EXPRESS supplies two to the Speed constructor during enum initialization. The constructor stores it in that instance's final days field. The accessor reads the attached value without relying on ordinal. The number therefore expresses delivery duration rather than the constant's position, which is one in this declaration.
How EnumNames produces its output
The first lookup exactly matches OPEN and returns that constant. The lowercase text does not match a declared name, so valueOf throws IllegalArgumentException and the catch prints the chosen message. This is a name-matching rule, not an automatic case-insensitive search. A user-input conversion method should make any permitted normalization explicit.
Model a closed set instead of arbitrary strings
A method accepting Stall can receive only declared Stall constants or null, while a method accepting String can receive any spelling. This makes enum types useful for states whose permitted choices are deliberately limited. Keep displayed labels separate from names when a user-facing translation may change. For practice, add a LARGE constant with an explicit width and iterate values to print each name and width. Reorder the declaration and explain which outputs change: iteration and ordinals follow the new declaration order, but the explicit widths remain attached to their chosen constants. That distinction is why explicit data fields are preferable to deriving business values from ordinal.
Collections designed for enum keys
EnumSet represents a set of enum constants, and EnumMap associates constants of one enum type with values. These specialized collections make the restricted key domain explicit. An EnumSet of permitted states is clearer than a group of unrelated boolean flags when the program needs to test membership. An EnumMap can associate each delivery speed with an additional external setting without making that setting mutable shared state inside the enum itself. As with ordinary collections, choose whether that mapping should be mutable or published through a controlled interface. The declared constants remain fixed even though a separate collection of them can change its membership.
Java Summary
- An enum defines a fixed set of named instances. It is suitable for a small closed set of states, categories or modes.
- Enum constants can pass arguments to constructors and hold fields. Each constant is an object of the enum type rather than an arbitrary integer code.
- Enum constructors are not public; callers use the declared constants instead of constructing new enum instances.
- values returns the constants in declaration order, while valueOf matches an exact constant name. Avoid storing ordinal as a durable identifier because changing declaration order changes its value.
- Continue with Java exercises, Java quizzes and the Java study roadmap.
Java Examples
Each example shows the code, the output it produces and what each part does.
Java Enums and Enum Constructors in a complete program
public class StallEnumValues {
enum Stall {
COMPACT(2), WIDE(4);
private final int width;
Stall(int width) {
this.width=width;
}
int metres() {
return width;
}
}
public static void main(String[] args) {
Stall stall = Stall.WIDE;
System.out.println(stall.name() + ": " + stall.metres() + " metres");
}
}WIDE: 4 metresLine-by-line explanation
- Line 14Evaluates
stall.name() + ": " + stall.metres() + " metres"and printsWIDE: 4 metres.
Enum constants carry constructor data
public class DeliverySpeeds {
enum Speed {
STANDARD(5), EXPRESS(2);
private final int days;
Speed(int days) {
this.days = days;
}
int days() {
return days;
}
}
public static void main(String[] args) {
System.out.println(Speed.EXPRESS.days());
}
}2Line-by-line explanation
- Line 13Evaluates
Speed.EXPRESS.days()and prints2.
Exact names are required for valueOf
public class EnumNames {
enum State {
OPEN, CLOSED
}
public static void main(String[] args) {
System.out.println(State.valueOf("OPEN"));
try {
State.valueOf("open");
}
catch (IllegalArgumentException e) {
System.out.println("unknown state");
}
}
}OPEN
unknown stateLine-by-line explanation
- Line 6Evaluates
State.valueOf("OPEN")and printsOPEN. - Line 11Evaluates
"unknown state"and printsunknown state.
Java FAQ
Can an enum implement an interface?
Yes. Enums can implement interfaces and provide methods for their contracts. They already have their enum superclass, so they cannot extend a custom class. Constant-specific class bodies can also specialize behavior when the design needs it.
Can enum values be compared with ==?
Yes. Each declared constant has a unique identity, so == is a natural comparison for enum values and safely handles a null operand. A null value is still not a declared enum constant and must be considered when calling methods.
Can I add enum constants while the program runs?
No. An enum's constants are fixed when the code is compiled. If users or administrators need to add categories, such as new product types, store them in a database table or a configuration file and model them with an ordinary class.
How do I find an enum constant by one of its field values?
Loop over values() and compare the field, or build a static Map from the field to the constant once, inside the enum, for fast repeated lookups. Return an Optional or throw a clear exception when no constant matches, because valueOf only looks up constant names.
How many times does an enum constructor run?
Once for each constant, when the enum class is first used. Every later reference to Stall.NORTH returns that same object, so the constructor never runs again. Keep enum constructors simple, because a failure there prevents the whole enum from loading.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Why is ordinal a poor durable storage code?
Can callers create Speed with new Speed(3)?
Java Quiz
2 questions to check what you learned.
What happens for State.valueOf("open") here?
- IllegalArgumentException
- It returns OPEN automatically
- It returns null
What does EXPRESS(2) initialize?
- The EXPRESS instance's days field through its constructor
- The ordinal of EXPRESS
- Every instance's shared static days field