Java
Programming
Data Types
Enum
Type Casting

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:

java
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

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():

java
1public Day intToDay(int dayIndex) throws IllegalArgumentException {
2    Day[] days = Day.values();
3    if (dayIndex < 0 || dayIndex >= days.length) {
4        throw new IllegalArgumentException("Invalid day index");
5    }
6    return days[dayIndex];
7}

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:

java
1public Day intToDay(int dayCode) {
2    switch (dayCode) {
3        case 1: return Day.SUNDAY;
4        case 2: return Day.MONDAY;
5        case 3: return Day.TUESDAY;
6        case 4: return Day.WEDNESDAY;
7        case 5: return Day.THURSDAY;
8        case 6: return Day.FRIDAY;
9        case 7: return Day.SATURDAY;
10        default: throw new IllegalArgumentException("Invalid day code");
11    }
12}

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.

MethodUse CaseProsCons
Using ordinal valuesWhen integers match the ordinal indicesSimple and less codeFragile, breaks if the order changes
Defining mapping logicWhen integers do not match ordinal indicesRobust against changes in the enumRequires 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.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms