skip to content

Enums

Java enums are full classes with fields, methods and per-constant behavior, not just named integers. Interviewers ask about them for singletons, exhaustive switches, and the specialized EnumSet and EnumMap.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

15

What is an enum in Java, and how do you declare one with a fixed set of constants?

level: juniorimportance: must knowfreq 80%

answer

  1. Fixed, finite set of named constant instances
  2. enum keyword; each constant is public static final, created once
  3. Implicitly extends java.lang.Enum -> no other superclass, but can implement interfaces
  4. Type-safe: compiler rejects ints/strings
  5. Compare with == (one singleton per constant)

basics

~20 s

An enum is a special class whose instances are a fixed, named set of constants. You declare it with the enum keyword and list the constants, e.g. enum Day { MONDAY, TUESDAY }. Each constant is one shared, type-safe object.

solid answer

~40 s

An enum is a special class type that defines a fixed, finite set of named constant instances. You write `enum Direction { NORTH, SOUTH, EAST, WEST }`. Each listed name is a public static final instance of that enum type, created once by the JVM. Because the set is closed and type-safe, you cannot pass an arbitrary int or string where a Direction is expected, and the compiler can check switch exhaustiveness. Enums are far safer than the old `public static final int` constant pattern: they have a real type, meaningful toString, and cannot collide or be confused with unrelated constants. Under the hood each enum implicitly extends java.lang.Enum, so it cannot extend another class, but it can implement interfaces. You reference a constant by name (Direction.NORTH) and compare them with ==.

go deeper

for a junior

Can declare a simple enum and reference a constant by name; knows enums replace magic int/string constants and are type-safe.

for a middle

Explains that each constant is a public static final singleton instance, that the enum extends java.lang.Enum, and why == is the right comparison.

for a senior

Articulates the design rationale (closed type, compiler-checked switch, no spoofed values), the single-inheritance constraint vs interface implementation, and null-safety of ==.

for a principal

Frames enums in API and domain-modeling decisions: when a closed enum vs an open extensible type is appropriate, serialization/versioning implications of adding constants, and migration from legacy int-constant code.

## What problem enums solve Before enums (Java 5, 2004), people represented a fixed set of choices with integer or string constants, the **int enum pattern**: ```java public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; ``` This is unsafe. The compiler sees only an `int`, so you can pass `99` or add two seasons together, and nothing complains. There is no namespace, no type, and printing the value shows a meaningless number. ## What an enum is An **enum** (short for *enumeration*) is a special kind of **class** whose set of instances is **fixed and known at compile time**. You declare it with the `enum` keyword and list the **constants** (the instances) by name: ```java public enum Season { WINTER, SPRING, SUMMER, FALL } ``` Each name — `WINTER`, `SPRING`, etc. — is automatically a **`public static final` instance** of type `Season`. The JVM creates exactly one object per constant, once, when the enum class is loaded. So `Season.WINTER` always refers to the same single object (it is a built-in singleton per constant). Key terms: - **Constant**: one of the named instances (`WINTER`). - **Type-safe**: the compiler enforces that only a `Season` value can be used where a `Season` is expected; you cannot substitute an int or a string. - **Instance**: a concrete object; here, each constant is one. ## Why it is a class, not just a list `Season` compiles to a real class that implicitly **extends `java.lang.Enum`**. Because Java has single inheritance of classes, an enum therefore **cannot extend any other class** — but it **can implement interfaces**. Every enum inherits useful behavior from `Enum`: a sensible `toString()` (returns the constant name), `name()`, `ordinal()`, and natural ordering. ## Using an enum ```java Season s = Season.WINTER; // reference a constant by name if (s == Season.WINTER) { ... } // compare with == (safe: one instance each) System.out.println(s); // prints WINTER (inherited toString) ``` You compare enum constants with `==` rather than `equals()` because each constant is a unique singleton — `==` is both correct and null-safe (`s == Season.WINTER` is false, not an NPE, when `s` is null). ## Where enums fit syntactically An enum is a top-level type (its own `.java` file if public) or a nested/member type. Its constant declarations must be the **first thing** in the body, ending with a semicolon if anything else (fields, methods) follows. ## Summary An enum gives you a closed, type-safe, self-documenting set of named singleton constants backed by a real class — replacing fragile int/string constants and enabling compiler-checked switches.

  • Why is == safe for comparing enum constants when it is risky for most objects?
    Because each enum constant is a single shared instance created once by the JVM, so reference equality (==) coincides with logical equality. It is also null-safe: comparing a null reference with == yields false instead of throwing NullPointerException, whereas null.equals(...) would throw.
  • Can an enum implement an interface?
    Yes. An enum already implicitly extends java.lang.Enum so it cannot extend another class, but it may implement one or more interfaces and provide the implementing methods, either shared across all constants or as constant-specific bodies.

saying these in an interview costs you the question

  • Calling an enum 'just a list of int constants' — it is a full class with type safety
  • Claiming an enum can extend another class (it cannot; it already extends Enum)
  • Saying you must use equals() to compare constants (== is correct and null-safe)
  • Thinking new instances of an enum can be created at runtime

context

open as a page

How do you use an enum in a Java switch statement, and what conveniences does switching on an enum give you?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Put the enum value in switch(value) and use the bare constant names (like MONDAY, not Day.MONDAY) in each case. The compiler knows the type, so you skip the prefix and it can warn if a case is missing.

open as a page

How do you add fields, a constructor, and methods to an enum, and why is the constructor implicitly private?

level: middleimportance: must knowfreq 70%

basics

~20 s

List each constant with constructor arguments in parentheses, then declare instance fields, a constructor, and methods after a semicolon. The constructor is implicitly private because you may not create new enum instances — the JVM creates them all at load time.

open as a page

What do the built-in enum methods values(), valueOf(), name(), and ordinal() do, and what are their costs and caveats?

level: middleimportance: must knowfreq 72%

basics

~20 s

values() returns an array of all constants in declaration order. valueOf("NAME") returns the constant with that exact name (throws if none). name() returns the constant's declared name as a String. ordinal() returns its zero-based position in the declaration list.

open as a page

Why is a single-element enum considered the best way to implement a singleton in Java?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Because the JVM guarantees exactly one instance of each enum constant, and that single instance survives reflection and serialization attacks for free. So enum Singleton { INSTANCE; } gives you a thread-safe, attack-proof singleton with no boilerplate.

open as a page

Why are type-safe enums preferred over the older int/String constant pattern, and what risks does that pattern carry?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Int/String constants give the compiler no type, so any wrong value or unrelated constant can be passed by mistake, and printing shows a meaningless number or raw string. Enums are a real type the compiler checks, print readable names, and can hold data and methods.

open as a page

An enum can carry fields and a constructor. How does that interact with ordinal(), name(), and constant-specific behavior?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Each constant can pass arguments to a private enum constructor to set its own fields, like Planet(mass, radius). name() returns the constant's identifier text and ordinal() its position. You read fields through getters; ordinal/name come for free.

open as a page

What are constant-specific method bodies in a Java enum, and how do they let each constant behave differently?

level: middleimportance: should knowfreq 55%

basics

~10 s

Each enum constant can supply its own version of a method by writing a body in curly braces after the constant. So PLUS and MINUS can each compute differently while sharing one method name.

open as a page

Can a Java enum implement an interface? How, and why is that useful?

level: middleimportance: should knowfreq 50%

basics

~10 s

Yes. An enum can use implements SomeInterface and provide the interface methods, either once for the whole enum or per constant. It cannot extend a class, but it can implement any number of interfaces.

open as a page

What is EnumMap, how does it work internally, and when should you choose it over HashMap?

level: middleimportance: should knowfreq 58%

basics

~20 s

EnumMap is a Map whose keys are constants of one enum type. Internally it is just an array indexed by each key's ordinal, so lookups and inserts are very fast and memory-light. Create it with new EnumMap<>(MyEnum.class). Keys iterate in declaration order.

open as a page

What is EnumSet, and why should you prefer it over HashSet when the elements are enum constants?

level: middleimportance: should knowfreq 62%

basics

~20 s

EnumSet is a Set built specifically for enum values. Internally it stores membership as bits, so it is much faster and uses far less memory than a HashSet of the same enums. Create one with factory methods like EnumSet.of(A, B) or EnumSet.allOf(MyEnum.class).

open as a page

How do enums guarantee one instance per constant, and why does that make the single-element enum a robust singleton?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The JVM creates each enum constant exactly once during thread-safe class initialization, and the language forbids new instances. A single-constant enum is therefore a singleton that is automatically thread-safe and resistant to reflection and serialization attacks.

open as a page

Java enums implicitly implement Comparable and Serializable. What ordering do they use, and what is special about enum serialization?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Enums sort by declaration order (their ordinal), and compareTo is final so you can't change it. They serialize by name, not by field state, so deserialization always returns the existing constant — identity is preserved.

open as a page

EnumSet and EnumMap rely on ordinal() internally. What risk does this create for your own code that depends on enum ordering, and how do you avoid it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

EnumSet/EnumMap use ordinal positions internally, which is fine and stays correct. The danger is in YOUR code: if you store or persist ordinal numbers and then reorder or insert enum constants, those numbers now point at the wrong constant. Persist the constant name, not its ordinal.

open as a page

When designing behavior that varies per enum constant, when should you use a switch (or EnumMap of handlers) versus constant-specific method bodies (polymorphism on the enum)?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

If the behavior naturally belongs to the enum itself and every constant must define it, give the enum an abstract method and override it per constant — the compiler then forces each new constant to provide behavior. If the behavior belongs to the caller or varies by use site, use a switch or an EnumMap of handlers there.

open as a page