Advertisement
Intermediate Java, Enums

What are the ordinal() and name() methods on an enum constant, and why is relying on ordinal() for persistence or serialization considered dangerous?

Short answer

ordinal() returns the zero-based position of a constant in its enum's declaration order, and name() returns the constant's declared identifier as a String -- persisting an enum's ordinal() value (e.g., storing it in a database) is dangerous because ordinal values are entirely…

Save Java mock interview
Advertisement
AModel answer
ordinal() returns the zero-based position of a constant in its enum's declaration order, and name() returns the constant's declared identifier as a String -- persisting an enum's ordinal() value (e.g., storing it in a database) is dangerous because ordinal values are entirely dependent on declaration order, meaning simply reordering, inserting, or removing a constant in the enum's source code (a seemingly harmless refactor) silently changes the meaning of every previously-persisted ordinal value, causing data corruption without any compiler warning; persisting name() instead is far safer since it's tied to the constant's actual identifier rather than its fragile positional order (though renaming a constant would still require a data migration, that's a much rarer and more deliberate change than reordering).
enum Priority { LOW, MEDIUM, HIGH }  // ordinals: LOW=0, MEDIUM=1, HIGH=2

// DANGEROUS: persisting ordinal()
int stored = Priority.HIGH.ordinal();  // stores 2

// If someone later reorders the enum to: LOW, HIGH, MEDIUM
// then ordinal 2 now means MEDIUM instead of HIGH -- silent data corruption!

// SAFER: persist name() instead
String stored2 = Priority.HIGH.name();  // stores "HIGH", immune to reordering
Real-world example
A team debugging why historical order priority data appeared to have silently changed meaning after a routine code refactor discovers the database had been storing Priority.ordinal() values, and a well-intentioned enum reordering during an unrelated change had silently invalidated the meaning of every previously stored value, prompting a migration to storing name() instead.
Likely follow-ups
  • What's the safest approach if you need a genuinely stable, explicit persisted value that's independent of both ordinal and name (like an explicit numeric code field)?
  • Why does Comparable's compareTo() implementation for enums use ordinal() despite this same fragility concern?
Related topics