Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

An enum maps external codes to constants with a static lookup map. Show the pattern and explain why a constructor cannot put itself into a static map of the same enum.

We build the lookup map once in a static field declared after the constants, for example private static final Map<String, Country> BY_CODE = Arrays.stream(values()).collect(Collectors.toUnmodifiableMap(c -> c.code, c -> c)), and expose fromCode() that returns an Optional or throws a clear exception. A constructor cannot put this into the map because enum constants are created first in the static initializer, before any other static field is initialized, so the map is still null; the compiler rejects a direct reference to a non-constant static field from an enum constructor for that reason.

Background to this question

Mapping external codes to enum constants is everywhere: ISO country codes from a partner, status codes from a payment provider, currency codes in a file. The obvious approach, registering each constant in a map from its own constructor, does not compile, and the reason teaches us how enum initialization really works. In this answer, we will recap the order in which an enum initializes, try the constructor approach and see why it fails, write the correct pattern, and then decide how unknown codes should be handled.

1A Quick Recap: How an Enum Initializes

An enum's constants are public static final fields, and the compiler creates them in the class's static initializer, the code that runs once when the class is first used. The rule that matters here is that the constants always come first. The Java language requires the constant list at the top of the enum body, and the compiler emits their creation before the initializers of any other static fields, in source order.

So while the constructor for the first constant runs, no other static field of the enum has been assigned yet. A static Map field is still null at that moment, even if its declaration says = new HashMap<>().

Step throughStatic initialization of enum Country
  1. Create DEconstructor runs, BY_CODE is still null
  2. Create FRconstructor runs, BY_CODE is still null
  3. Create USconstructor runs, BY_CODE is still null
  4. Build $VALUESthe array behind values()
  5. Initialize BY_CODEnow values() returns all three constants

5 steps in order. Play them, or step through them one at a time.

Constants are created before any other static field, so only code that runs after them can use the map.

2The Failing Approach: Registering From the Constructor

The tempting version puts each constant into the map from its own constructor.

Java
enum Country {
DE("276"), FR("250"), US("840");
private static final Map<String, Country> BY_CODE = new HashMap<>();
final String code;
Country(String code) {
this.code = code;
BY_CODE.put(code, this); // error: illegal reference to static field from initializer
}
}

The compiler rejects it. The Java Language Specification makes it a compile-time error to refer to a static field of an enum from its constructors, instance initializers or instance field initializers, unless the field is a compile-time constant such as a static final int with a literal value. The rule exists precisely because such code would see the field before it is initialized.

We can see what the compiler is protecting us from by hiding the access behind a static method, which the compiler does not check.

3What Happens If We Trick the Compiler

A static helper method is allowed, so this version compiles. It fails when the class is first used.

Java
enum Country {
DE("276"), FR("250"), US("840");
private static final Map<String, Country> BY_CODE = new HashMap<>();
final String code;
Country(String code) { this.code = code; register(this); }
private static void register(Country c) { BY_CODE.put(c.code, c); } // BY_CODE is null here
}
Country.valueOf("DE");
// java.lang.ExceptionInInitializerError
// Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Map.put(Object, Object)" because "Country.BY_CODE" is null

The NullPointerException happens inside the static initializer, so the JVM wraps it in ExceptionInInitializerError and marks the class as failed. Every later attempt to use Country then throws NoClassDefFoundError, which is a confusing error to meet in production far away from the real cause. This is exactly the situation the compile-time rule prevents.

4The Correct Pattern

The fix is to build the map after the constants exist, in the initializer of a static field declared below them. At that point values() returns every constant, so we can stream over them once.

Java
public enum Country {
DE("276"), FR("250"), US("840");
private static final Map<String, Country> BY_CODE =
Arrays.stream(values())
.collect(Collectors.toUnmodifiableMap(c -> c.code, c -> c));
private final String code;
Country(String code) { this.code = code; }
public String code() { return code; }
public static Optional<Country> fromCode(String code) {
return Optional.ofNullable(BY_CODE.get(code));
}
}
Country.fromCode("250"); // Optional[FR]
Country.fromCode("999"); // Optional.empty

Three details are deliberate. toUnmodifiableMap returns a map nobody can change, so the lookup table is as fixed as the enum. It also throws IllegalStateException at class initialization if two constants share a code, which turns a copy-paste mistake into an immediate failure instead of a silently wrong lookup. And the map is built once, so fromCode() is a single hash lookup with no allocation.

One caution about fromCode(): Map.get(null) is not allowed on unmodifiable maps and throws NullPointerException, so if the input may be null we check for it first.

5Deciding How Unknown Codes Are Handled

The last decision is the important one in real systems. External systems add codes on their own schedule, so sooner or later fromCode() will receive a code our enum does not know. There are three reasonable answers, and the choice should be made deliberately for each enum.

Java
// Strict: the caller cannot proceed without a known country
public static Country fromCodeOrThrow(String code) {
return fromCode(code).orElseThrow(() ->
new IllegalArgumentException("Unknown country code '" + code + "', known: " + BY_CODE.keySet()));
}
// Tolerant: keep processing, with an explicit placeholder
public static Country fromCodeOrUnknown(String code) {
return fromCode(code).orElse(UNKNOWN); // needs an UNKNOWN constant in the enum
}

Strict handling suits data we validate on input, such as an API request, where rejecting the request with a clear message is correct. Tolerant handling suits data we must not lose, such as events from another service, where crashing the consumer on a new code would stop everything; an explicit UNKNOWN constant plus a log line or metric makes the gap visible. Returning Optional lets each caller choose. What we avoid is a lookup that returns null without saying so, because the NullPointerException then appears far from the cause.

6Follow-up questions

Could a nested holder class make the constructor approach work?

Yes. If the map lives in a private static nested class, the constructor's first access triggers initialization of that nested class, which does not depend on the enum, so the map exists. It works, but the stream over values() after the constants is simpler and makes duplicates fail loudly, so we prefer it.

Why does the rule allow compile-time constants?

Because a compile-time constant, such as static final int MAX = 10, is inlined by the compiler at every use, so reading it never touches the uninitialized field at run time.

Is a switch better than a map for a small enum?

For three constants, a switch or a loop over a cached array is fine and fast. The map wins as the enum grows, and toUnmodifiableMap's duplicate check is valuable at any size.

7Conclusion

In this answer, we saw that an enum's constants are created first in its static initializer, before any other static field, so a static map is still null while the constructors run. The compiler forbids referring to non-constant static fields from enum constructors for that reason, and tricking it with a static method leads to ExceptionInInitializerError. The correct pattern builds an unmodifiable map once, after the constants, with a stream over values(), exposes fromCode() returning Optional or throwing a clear exception, and decides deliberately how unknown external codes are handled.

What to say in the interviewAbout 80 seconds aloud

Open with

I build the map in a static field declared after the constants: private static final Map of String to Country BY_CODE equals Arrays.stream of values, collected with Collectors.toUnmodifiableMap keyed by code.

Then, if they want more

Then fromCode does one lookup and returns an Optional, or I offer a variant that throws an IllegalArgumentException naming the bad code. toUnmodifiableMap also fails at startup if two constants share a code, which catches copy-paste mistakes. The constructor cannot register itself because of initialization order.

Enum constants are created first in the static initializer, before any other static field is assigned, so while DE's constructor runs, BY_CODE is still null. The language makes it a compile-time error to reference a non-constant static field from an enum constructor for exactly that reason.

If you hide the access behind a static method, it compiles but throws a NullPointerException during class initialization, which surfaces as ExceptionInInitializerError and then NoClassDefFoundError on every later use.

Finally, I decide how unknown codes are handled, because external systems add codes before we do: strict rejection for validated input like API requests, and an explicit UNKNOWN constant with a metric for data we must not drop, like events.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An enum maps external codes to constants with a static lookup map. Show the pattern and...": https://scrivio-interview-library.netlify.app/java/enums/f8a7c1b339/