The Analogy: The Colour-Coded Cylinders In A Welding Bay
The bay behind the fabrication shop holds gas cylinders, and there are exactly six kinds. Black shoulder is oxygen, maroon is acetylene, grey is argon, brown is helium, green is carbon dioxide, red is propane. That list is not the bay's decision. It comes from a standard, it is printed on a chart bolted to the wall, and a welder who wants a seventh gas does not get to paint a cylinder and invent one. The set is closed, and everybody who works in the bay can name every member of it.
A colour is not merely a label stuck on the outside. Each one carries its own facts: a full pressure, a handling rule, and a valve thread. Fuel gases are cut with a left-hand thread and oxidisers with a right-hand thread, so a fuel regulator physically will not screw onto an oxygen bottle -- the mistake is stopped by the shape of the metal rather than by somebody noticing. And there is exactly one kind of maroon cylinder. Two maroon bottles standing side by side are two bottles, but they are the same entry on the chart, and asking "are these the same gas?" is answered by comparing the entries, not by reading the labels letter by letter.
The chart on the wall is the other half of the arrangement. It lists all six in a fixed order, so the storeman can walk the row and count, and so a new starter can be handed the chart rather than a list of six things to memorise. The order on the chart is genuinely useful: the racks are laid out to match it, the stock sheet columns follow it, and the daily count goes left to right without anybody thinking about it.
Then somebody builds a stores system that records each bottle by the position it sits in on the rack instead of by its colour code. It works, and it keeps working right up until 2026, when helium is added and the rack is renumbered to keep the chart order intact. Now every historical record is off by one from the fourth position onward. Yesterday's "position 4" meant carbon dioxide; today it means helium. Worse, yesterday's "position 5" meant propane and today it means carbon dioxide -- a left-hand-thread fuel gas has quietly become a right-hand-thread oxidiser in the paperwork, and nothing anywhere threw an error. The colour code was on every bottle the whole time. The system chose to key on the position because the position was already a number.
Syntax or Core Structure
An enum declares a closed set of named constants. Each constant may carry its own data through a constructor, and the enum may hold methods like any other class.
enum Cylinder {
OXYGEN("black", 230, false),
ACETYLENE("maroon", 15, true),
ARGON("grey", 200, false),
CO2("green", 50, false),
PROPANE("red", 7, true); // semicolon required once members follow
private final String shoulder;
private final int barFull;
private final boolean fuel;
Cylinder(String shoulder, int barFull, boolean fuel) { // implicitly private
this.shoulder = shoulder;
this.barFull = barFull;
this.fuel = fuel;
}
public String shoulder() { return shoulder; }
public int barFull() { return barFull; }
public boolean fuel() { return fuel; }
public String thread() { return fuel ? "left-hand" : "right-hand"; }
}
public class WeldingBay {
public static void main(String[] args) {
Cylinder c = Cylinder.ACETYLENE;
System.out.println("name " + c.name());
System.out.println("ordinal " + c.ordinal());
System.out.println("shoulder " + c.shoulder());
System.out.println("bar " + c.barFull());
System.out.println("thread " + c.thread());
System.out.println("count " + Cylinder.values().length);
System.out.println("parsed " + Cylinder.valueOf("ARGON").shoulder());
System.out.println("same " + (c == Cylinder.valueOf("ACETYLENE")));
System.out.println("tostring " + Cylinder.CO2);
}
}
Output:
name ACETYLENE
ordinal 1
shoulder maroon
bar 15
thread left-hand
count 5
parsed grey
same true
tostring CO2
Five things in that output are worth pinning down now. name() returns the identifier exactly as written, and toString() returns the same thing until you override it. ordinal() is the zero-based position in the declaration list, which is why ACETYLENE reports 1 -- remember that number is a property of the order you typed, not of acetylene. values() hands back every constant, so the set can be walked without a hardcoded list. valueOf turns text back into a constant. And the same line is the important one: valueOf("ACETYLENE") did not build a second acetylene, it returned the one and only instance, so == is true.
Technical Depth: What The Compiler Generates, Why == Is The Right Comparison, And The Two Ways A Constant Carries Behaviour
What enum Cylinder actually compiles to
An enum is a class. The keyword is a request for a very specific class that you are not allowed to write by hand, and knowing what arrives with it explains most of the rules.
| You write | The compiler provides | Consequence |
|---|---|---|
enum X | a class extending java.lang.Enum | the one extends slot is spent, but implements is free |
| a constant | a public static final X field | exactly one instance per constant, built at class init |
| a constructor | private access, always | new X(...) never compiles, from anywhere |
| nothing | values() and valueOf(String) | values() returns a fresh copy of the array on every call |
| nothing | name(), ordinal(), compareTo | compareTo orders by ordinal, and it is final |
| nothing | final equals, hashCode and clone | identity semantics cannot be overridden, and clone throws |
Because implements is still free, an enum can implement interfaces, which is how a closed set of constants ends up satisfying a capability. Because the constructor is private, the set really is closed -- there is no reflection-free way to add a member, and the instances are created once during class initialisation and never again.
That initialisation order produces one compile error people meet exactly once and never forget. Constants are built before any static field of the enum is assigned, so an enum constructor is forbidden from touching a static field of its own enum: the compiler reports an illegal reference to a static field from an initializer. Any name-to-constant lookup table therefore has to be filled in a static block, which runs after every constant exists.
Why == is the right comparison, and equals is the trap
One instance per constant means identity comparison is not an optimisation, it is the correct semantics.
enum Trade { WELDER, FITTER }
enum Gas { OXYGEN, ARGON }
public class Compare {
public static void main(String[] args) {
Trade t = Trade.WELDER;
Trade u = Trade.valueOf("WELDER");
System.out.println("identity " + (t == u));
System.out.println("equals " + t.equals(u));
System.out.println("crossed " + t.equals(Gas.OXYGEN));
Trade n = null;
System.out.println("null safe " + (n == Trade.FITTER));
}
}
Output:
identity true
equals true
crossed false
null safe false
The first two lines agree, so it looks like a free choice. The third shows why it is not. t.equals(Gas.OXYGEN) compiles happily and returns false forever, because equals takes an Object and comparing a welder to oxygen is a perfectly legal question with a boring answer. Write t == Gas.OXYGEN instead and the compiler refuses it outright as incomparable types. The version that catches your bug at build time is the shorter one. The fourth line adds the other reason: == on a null reference is false, while n.equals(...) would have thrown.
The two ways a constant carries behaviour
Data belongs in final fields set by the constructor. Behaviour has two homes, and the choice between them decides what happens when somebody adds a constant next year.
import java.util.Locale;
enum Handling {
UPRIGHT {
@Override public String rule() { return "store vertical, chain to wall"; }
},
VENTED {
@Override public String rule() { return "store outdoors, cage vented"; }
},
ANY {
@Override public String rule() { return "no special rule"; }
};
public abstract String rule(); // every constant must answer
}
public class Bodies {
public static void main(String[] args) {
for (Handling h : Handling.values()) {
System.out.printf(Locale.ROOT, "%-9s %s%n", h.name(), h.rule());
}
System.out.println("declaring " + Handling.UPRIGHT.getDeclaringClass().getSimpleName());
System.out.println("anon " + (Handling.UPRIGHT.getClass() != Handling.class));
}
}
Output:
UPRIGHT store vertical, chain to wall
VENTED store outdoors, cage vented
ANY no special rule
declaring Handling
anon true
An abstract method plus a body per constant is the shape that defends itself: add a fourth constant without a rule() and the enum does not compile. The alternative -- one method containing a switch -- compiles fine with the new constant missing and returns whatever the default branch says, which is the same bargain the previous two lessons took apart.
The last two output lines show the machinery. A constant with its own body is an anonymous subclass of the enum, so getClass() is not Handling.class and the enum type itself is not final. getDeclaringClass() is the method that reliably names the enum, which matters when you are logging or switching on type.
Switching on an enum, and the default clause you should usually refuse to write
In a switch over an enum the label is the bare constant name; the type comes from the selector, so there is nothing to qualify. What matters is whether you write a default.
// Statement form. The default clause silently absorbs anything added later.
static String handlingOld(Cylinder c) {
switch (c) {
case ACETYLENE: return "upright, chained";
case PROPANE: return "outdoor cage";
default: return "standard rack";
}
}
// Expression form with no default. Adding a constant breaks the build right here.
static String handlingNew(Cylinder c) {
return switch (c) {
case ACETYLENE -> "upright, chained";
case PROPANE -> "outdoor cage";
case OXYGEN, ARGON, CO2 -> "standard rack";
};
}
A switch expression over an enum that covers every constant needs no default, and that is the single best reason to prefer the expression form here: the day somebody adds a seventh gas, every switch that must be reviewed fails to compile, and every switch that genuinely did not care carries a default on purpose. The statement form with a default gives you the opposite -- silence, and a new gas handled as "standard rack" because nobody was asked.
There is one more safeguard worth knowing about. If you compile an exhaustive switch expression and then run it against a recompiled enum that has gained a constant, the compiler's synthetic fallback throws IncompatibleClassChangeError rather than picking a branch. A loud failure at the moment of mismatch beats a plausible wrong answer.
EnumMap, EnumSet, and the one place ordinal belongs
The ordinal is a genuinely good array index. It is a terrible database column. The JDK draws that line for you with two collections built specifically for enum keys.
| Need | Use | Why |
|---|---|---|
| A map keyed by an enum | EnumMap | an array indexed by ordinal, iterated in declaration order, no hashing and no key boxing |
| A set of enum values | EnumSet | a bit vector; a single long covers an enum of up to 64 constants |
| A constant's own data | final fields set in the private constructor | read straight off the constant, with no parallel table to keep in step |
| A constant's own behaviour | an abstract method plus a body per constant | the compiler forces every future constant to answer |
Both collections iterate in ordinal order, which is where using the ordinal is entirely correct: it lives inside one run of one program and is never written down. EnumSet also gives you noneOf, allOf, of, range and complementOf, which express things like "every fuel gas" or "everything except propane" more clearly than a loop and a HashSet.
The discipline about name() and ordinal()
Never persist ordinal(). Insert a constant anywhere except the end and every stored value now names a different thing, exactly as the rack numbering did in the welding bay -- and no exception is thrown, because the old number is still a valid index.
name() is safer and still not safe. It is final and returns the identifier verbatim, so it survives reordering and insertion; it does not survive a rename, and renaming a constant is a refactor an IDE will do for you without a word about the database. The version that survives both is an explicit code field you assign yourself and never change, with a static lookup built from it.
Two smaller rules follow from the same idea. Do not parse toString(), because it is overridable and valueOf matches name(), so an overridden toString breaks the round trip. And remember that valueOf does not return null for an unknown name -- it throws IllegalArgumentException, and throws NullPointerException for a null argument, so external input needs a lookup that reports the bad value rather than a bare call in the middle of a parser.
Real World Example: A Cylinder Store Where One Table Was Keyed By Position And A Fuel Gas Became An Oxidiser
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
enum Gas {
OXYGEN("OX", "black", 230, false),
ACETYLENE("AC", "maroon", 15, true),
ARGON("AR", "grey", 200, false),
HELIUM("HE", "brown", 200, false), // added in 2026, in chart order
CO2("CD", "green", 50, false),
PROPANE("PR", "red", 7, true);
private static final Map<String, Gas> BY_CODE = new HashMap<>();
static { // runs after every constant exists
for (Gas g : values()) {
BY_CODE.put(g.code, g);
}
}
private final String code;
private final String shoulder;
private final int barFull;
private final boolean fuel;
Gas(String code, String shoulder, int barFull, boolean fuel) {
this.code = code;
this.shoulder = shoulder;
this.barFull = barFull;
this.fuel = fuel;
}
String code() { return code; }
String shoulder() { return shoulder; }
int barFull() { return barFull; }
boolean fuel() { return fuel; }
String thread() { return fuel ? "left-hand" : "right-hand"; }
static Gas fromCode(String c) {
Gas g = BY_CODE.get(c);
if (g == null) {
throw new IllegalArgumentException("unknown gas code " + c);
}
return g;
}
}
public class CylinderStore {
// Three records written before HELIUM existed, keyed by ordinal(). This is the bug.
private static final int[] LEGACY_ORDINALS = { 0, 3, 4 };
// The same three records, keyed by the code printed on the bottle. This is the fix.
private static final String[] LEGACY_CODES = { "OX", "CD", "PR" };
static String handling(Gas g) {
switch (g) { // no compile error when a gas is added
case ACETYLENE: return "upright, chained";
case PROPANE: return "outdoor cage";
default: return "standard rack";
}
}
public static void main(String[] args) {
System.out.println("constants " + Gas.values().length);
for (int i = 0; i < LEGACY_ORDINALS.length; i++) {
Gas byOrdinal = Gas.values()[LEGACY_ORDINALS[i]];
Gas byCode = Gas.fromCode(LEGACY_CODES[i]);
System.out.println(String.format(Locale.ROOT,
"row %d ord %d -> %-9s code %s -> %-9s %s",
i, LEGACY_ORDINALS[i], byOrdinal.name(),
LEGACY_CODES[i], byCode.name(),
byOrdinal == byCode ? "MATCH" : "WRONG"));
}
Gas resolved = Gas.values()[4]; // what the third legacy record now decodes to
Gas actual = Gas.fromCode("PR"); // what the bottle actually is
System.out.println("resolved " + resolved.name() + " " + resolved.thread()
+ " " + resolved.barFull() + " bar");
System.out.println("actual " + actual.name() + " " + actual.thread()
+ " " + actual.barFull() + " bar");
System.out.println("handle AC " + handling(Gas.ACETYLENE));
System.out.println("handle HE " + handling(Gas.HELIUM));
Map<Gas, Integer> stock = new EnumMap<>(Gas.class);
stock.put(Gas.PROPANE, 2); // inserted third
stock.put(Gas.OXYGEN, 6); // inserted second
stock.put(Gas.ACETYLENE, 3); // inserted first
StringBuilder walk = new StringBuilder();
for (Map.Entry<Gas, Integer> e : stock.entrySet()) {
walk.append(e.getKey().code()).append(e.getValue());
}
System.out.println("enummap " + walk);
EnumSet<Gas> fuels = EnumSet.noneOf(Gas.class);
for (Gas g : Gas.values()) {
if (g.fuel()) {
fuels.add(g);
}
}
System.out.println("fuels " + fuels);
boolean rejected;
try {
Gas.valueOf("NITROGEN");
rejected = false;
} catch (IllegalArgumentException ex) {
rejected = true;
}
System.out.println("rejected " + rejected);
}
}
Output:
constants 6
row 0 ord 0 -> OXYGEN code OX -> OXYGEN MATCH
row 1 ord 3 -> HELIUM code CD -> CO2 WRONG
row 2 ord 4 -> CO2 code PR -> PROPANE WRONG
resolved CO2 right-hand 50 bar
actual PROPANE left-hand 7 bar
handle AC upright, chained
handle HE standard rack
enummap OX6AC3PR2
fuels [ACETYLENE, PROPANE]
rejected true
Most of this enum is doing exactly what an enum is for. Every constant carries its own code, shoulder colour, full pressure and fuel flag as final fields, so thread() can be derived rather than looked up in a table somebody has to maintain. fromCode is built once in a static block -- it could not have been built in the constructor, because an enum constructor may not touch a static field of its own enum -- and it throws with the offending code in the message instead of returning null. EnumMap and EnumSet are used where they belong: the stock walk came out in chart order even though the entries went in backwards, and fuels printed the two left-hand-thread gases in declaration order without any sorting.
Now read rows one and two, which are the whole point. A record written when the enum had five constants stored the number 3 to mean carbon dioxide. Helium was added in chart position four, and that same number 3 now decodes to helium. The next record stored 4 for propane, and 4 now decodes to carbon dioxide. No exception was thrown at any point, because 3 and 4 are still perfectly valid indexes into a six-element array. The code column, running down the same three rows, resolved correctly every time -- OX, CD and PR mean what they have always meant, because they were chosen to be stable and nothing about the declaration order can move them.
The resolved and actual lines spell out what that costs. The paperwork now says the bottle in that bay is carbon dioxide: right-hand thread, 50 bar. The bottle is propane: left-hand thread, 7 bar. Every downstream decision -- which regulator to issue, which cage it may be stored in, what the pressure reading should be -- is being taken from the wrong row of the chart. And notice the second failure sitting immediately below it. handling has a default branch, so helium arrived into a system whose handling rules had never been reviewed for it and was quietly filed as "standard rack". The compiler had all the information needed to stop that and was not asked. If handling had been an exhaustive switch expression with no default, adding HELIUM would have failed the build.
The remaining limits are worth naming. Gas.values() is called inside the loop and again below it, and each call copies the backing array, so a hot loop over an enum should hoist it. fromCode throws IllegalArgumentException for bad input, which is right for a programming error and wrong for a line read out of a supplier's CSV -- that caller wants a method returning Optional<Gas>. BY_CODE is a HashMap and nothing stops two constants being given the same code, in which case one silently overwrites the other at class-initialisation time with no error at all. The record format has no version field, so there is no way to tell an ordinal written in 2025 from one written in 2026, which means this bug cannot even be fixed by migration without a separate source of truth. And the six constants are hardcoded in source: a gas the standard adds next year needs a recompile and a redeploy, which is the price of a closed set and the reason an enum is the wrong tool for a list that customers can edit.
Common Mistakes
- Persisting
ordinal(). A column of ordinals is a column of positions in a source file.
Insert a constant anywhere but the end and every stored value silently means something else, with no exception, because the old number is still a valid index. Store a code you control.
- Touching a static field of the enum from its constructor. Constants are created before
static fields are assigned, so BY_CODE.put(code, this) inside the constructor is a compile error about an illegal reference to a static field from an initializer. Build lookup tables in a static block.
- Comparing enums with
equalsinstead of==. Both work within one enum, but
trade.equals(Gas.OXYGEN) compiles and returns false forever, whereas trade == Gas.OXYGEN is rejected as incomparable types. Choosing equals throws away the only comparison the compiler can check.
- Expecting
valueOfto return null. It throwsIllegalArgumentExceptionfor an unknown
name and NullPointerException for null. Any value coming from a file, a form or a wire needs a wrapper that reports the bad input rather than a bare valueOf inside a parser.
- Round-tripping through
toString().name()isfinal;toString()is overridable and
often overridden for display. valueOf matches name(), so the moment somebody writes a friendlier toString the parse stops working for reasons that look unrelated.
- Writing
defaultin every switch over an enum. Adefaultmakes the switch total
forever, which means a constant added next year is handled by whatever that branch happens to say. Prefer an exhaustive switch expression with no default so the build breaks instead.
- Reaching for
HashMapandHashSetwith enum keys.EnumMapis an array indexed by
ordinal and EnumSet is a bit vector, so both are smaller, faster, and iterate in declaration order with no hashing and no boxing. There is almost no reason to choose the general collections here.
- Calling
values()in a loop or a hot method. Every call copies the backing array so that
callers cannot mutate the real one. Hoist it into a local, or into a private static final array the enum keeps to itself.
- Giving an enum a mutable field. Each constant is one instance that lives as long as the
class is loaded, so a non-final field on an enum is a global variable with no owner and no synchronisation. Enum constants should be immutable, and anything that changes belongs in an EnumMap held by whoever changes it.
Best Practices
- Give each constant its data through
finalfields and a private constructor. A parallel
array or a switch returning the pressure is a second thing to keep in step with the first; a field cannot drift from the constant it belongs to.
- Compare with
==. It is null-safe, it reads as the identity check it actually is, and it
turns a comparison across two enum types into a compile error instead of a permanent false.
- Persist an explicit code you assign, never
ordinal()and preferably notname().
Ordinals break on insertion and name() breaks on rename, and an IDE will do that rename without mentioning the database.
- Prefer an exhaustive switch expression with no
defaultover an enum. That single choice
converts "somebody added a gas" from a silent behaviour change into a list of every place that now needs a decision.
- Use
EnumMapandEnumSetfor anything keyed on or collected from an enum. They are the
one place the ordinal is the right tool, because it never leaves the running program.
- Use an
abstractmethod with a body per constant when every constant genuinely differs.
It costs a few more lines than a switch and it makes the compiler demand an answer from the seventh constant somebody adds after you have left.
- Keep enum constants immutable. All fields
final, no setters, and no lazily cached state;
a constant is visible to every thread in the process for the lifetime of the class.
- Build name and code lookups in a
staticblock, and give the caller a total function.
Return Optional for parsing external input and throw with the offending value only where a bad code means a bug in your own code.
Practice Exercises
- The Renumbered Rack. Write the five-constant version of
Gaswithout HELIUM, store the
ordinals of carbon dioxide and propane in an int[], and print what they decode to. Now add HELIUM in chart order and rerun without touching the stored numbers -- predict both decoded names before you run it. Repeat the whole exercise storing name() instead, then rename CO2 to CARBON_DIOXIDE and rerun. Finish by writing the version with a stable code and explain in two sentences what each of the three schemes survives.
- The Switch That Should Have Broken. Rewrite
handlingas an arrow-form switch expression
covering all six constants with no default, confirm it compiles, then add a seventh gas and record the exact compile error. Put the default back and rerun with the seventh gas to see what it reports instead. Then explain, in terms of who reads the error and when, why the version that fails the build is the safer one to ship.
- The Constant That Answers For Itself. Convert
handlinginto anabstractmethod on
Gas with a body on every constant, and check that adding a constant without a body fails to compile. Then add a non-final int issues field to Gas, increment it from two different methods, print it, and explain why that counter is a global variable -- and rewrite it as an EnumMap<Gas, Integer> owned by the store instead.