HOWTO · Java

How to Convert Enum to Int in Java

This tutorial demonstrates how to convert Enum to Int in Java.

On this page

Java’s ordinal() gives an enum constant’s zero-based declaration position. For a number that must keep the same meaning as constants change, assign an explicit integer in the enum or maintain a separate Map. The right choice depends on whether position, a stable code, or an external mapping is what your data represents.

Convert an enum constant to an int with ordinal()

Every enum constant has an ordinal() value: the first declared constant is 0, the next is 1, and so on. This is useful when the declaration position itself is meaningful, such as a temporary index within one program. It is fragile for persisted data or public interfaces: inserting or reordering constants changes later values, so avoid treating ordinal values as general-purpose codes. The Java SE Enum API documentation defines this value as the constant’s position in its declaration and notes that most programmers have no use for this method, supporting its limited use as a general-purpose code.

Run this example:

public class EnumOrdinalExample {
  enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY }

  public static void main(String[] args) {
    int position = Day.WEDNESDAY.ordinal();
    System.out.println("WEDNESDAY position: " + position);
  }
}

Observed output:

WEDNESDAY position: 3

Assign stable integers with a custom enum field

Give each constant an explicit field when its integer is a stable code you control. A constructor assigns the value once, and a getter exposes it. Reordering the constants does not change these numbers; changing a number still changes the mapping, so treat codes already stored or exchanged with another system as part of that system’s contract.

public class EnumCodeExample {
  enum Day {
    SUNDAY(10), MONDAY(20), WEDNESDAY(40);

    private final int code;

    Day(int code) {
      this.code = code;
    }

    int code() {
      return code;
    }
  }

  public static void main(String[] args) {
    int code = Day.WEDNESDAY.code();
    System.out.println("WEDNESDAY code: " + code);
  }
}

The values are deliberately distinct from ordinal positions. The enum owns the mapping, so callers use Day.WEDNESDAY.code() rather than depending on declaration order.

Use a Map when mappings belong outside the enum

Use a Map<Day, Integer> when the association is configured or maintained separately from the enum, for example by a surrounding component. Check for a missing key before unboxing the returned Integer: Map.get returns null when no mapping exists, and assigning that result directly to an int would fail at runtime.

import java.util.HashMap;
import java.util.Map;

public class EnumMapExample {
  enum Day { SUNDAY, MONDAY, WEDNESDAY }

  public static void main(String[] args) {
    Map<Day, Integer> codes = new HashMap<>();
    codes.put(Day.SUNDAY, 10);
    codes.put(Day.MONDAY, 20);
    codes.put(Day.WEDNESDAY, 40);

    Integer code = codes.get(Day.WEDNESDAY);
    if (code != null) {
      System.out.println("WEDNESDAY code: " + code);
    }
  }
}

The enum key prevents spelling mistakes in keys, while the map’s owner is responsible for populating and maintaining the entries. If all constants always share the same fixed mapping, an enum field keeps that invariant alongside the constants.

Convert an int back to an enum

An explicit code does not provide an automatic reverse conversion. Search the enum constants for a matching field, and define what an unknown integer means. This example returns null when there is no match; a caller that prefers another policy can return an Optional<Day> or report an error at its boundary.

public class EnumReverseExample {
  enum Day {
    SUNDAY(10), MONDAY(20), WEDNESDAY(40);

    final int code;

    Day(int code) {
      this.code = code;
    }

    static Day fromCode(int code) {
      for (Day day : values()) {
        if (day.code == code) {
          return day;
        }
      }
      return null;
    }
  }

  public static void main(String[] args) {
    Day day = Day.fromCode(40);
    if (day != null) {
      System.out.println("Code 40: " + day.name());
    }
  }
}

For a small enum, scanning values() is straightforward. If reverse lookups are frequent or the enum is large, build a reverse map once and ensure duplicate codes cannot silently select the wrong constant.

What valueOf() does (and does not do)

Day.valueOf("WEDNESDAY") looks up the enum constant whose declared name exactly matches the string. It returns a Day, not an integer. Calling .ordinal() afterward produces the same declaration-order number as Day.WEDNESDAY.ordinal(); valueOf() does not make that number stable. The lookup is case-sensitive and requires a matching name, so it is suitable for converting a known enum name, not an arbitrary numeric code.

Choose a mapping that fits your data

  • Use ordinal() only when declaration position is itself the intended value and the number is not a lasting external code.
  • Use a custom enum field when each constant has a fixed numeric meaning. This keeps the mapping with the enum and is usually the clearest choice for stable codes.
  • Use a Map when another component owns the mapping or it is loaded and maintained separately. Handle missing entries explicitly.
  • For integer-to-enum conversion, define the unknown-code behavior and use the same explicit mapping in both directions.

Avoid changing numeric codes after they have been persisted or sent across an interface unless that interface defines a migration. Keep the mapping documented where it is owned so future changes preserve the meaning of existing data.