Convert an int to an enum in Java
Codemia Knowledge Hub ·
Java does not let you cast an int to an enum. You convert it yourself, either by indexing into the enum's values() array when the integer is the constant's position (its ordinal), or by writing a method that maps specific integer codes to constants. This comes up when enums are serialized as numbers or exchanged with databases and external systems that have no enum type.
How Java enums are built
An enum is a special class type that implicitly extends java.lang.Enum:
Each constant is a public static final instance of the Day class.
Converting by ordinal with values()
Every constant has an ordinal, starting at 0 for the first declared one. If your integer is that position, look it up in values():
The method gets all Day values, rejects indexes outside the array, and returns the matching constant.
Converting with an explicit mapping
If the integer is not the ordinal, or the codes do not line up with declaration order (for example, days numbered from 1), map them explicitly:
Why ordinals are fragile
The ordinal approach depends on the constants never changing order. Reordering them, or inserting a new constant in the middle, silently changes which integer maps to which value. An explicit mapping is more verbose but survives those changes.
| Method | Use Case | Pros | Cons |
| Using ordinal values | When integers match the ordinal indices | Simple and less code | Fragile, breaks if the order changes |
| Defining mapping logic | When integers do not match ordinal indices | Robust against changes in the enum | Requires more code, more maintenance |
Pick based on whether the integers are guaranteed to track declaration order and how much the enum is likely to change.
Related reading
- Cast ListT to ListInterface
- Cast Object to Generic Type for returning
- Catch a thread's exception in the caller thread?
- Cause buildOutput.apkData must not be null
- Cause ERROR Recursive call to appender. Is there a way to solve it?
- Caused by org.apache.logging.log4j.LoggingException log4j-slf4j-impl cannot be present with log4j-to-slf4j
- Causes of getting a java.lang.VerifyError
- Change database schema used by Spring Boot
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.