Why prefer enums over int/String constants, and how do you put behavior in an enum?
Reviewed by Gurusankar M.
β‘ Short Answer
Enums are type-safe, exhaustively switchable, serializable singletons. Unlike int/String constants they can't take an invalid value, and they can carry fields and abstract methods β turning a switch into polymorphism.
βCoffee Chat Question
Concept Made Simple
βWhy prefer enums over int/String constants, and how do you put behavior in an enum?β
π§ Mind Map Answer
Remember It Faster
An int STATUS_ACTIVE = 1 accepts any int; an enum Status { ACTIVE, ... } accepts only valid members. Add a field/method and each constant becomes a tiny strategy object.
β¨οΈHands-on Keyboard
Learn by Doing
enum Plan {
FREE(0), PRO(999), ENTERPRISE(4999);
private final int priceCents;
Plan(int c) { this.priceCents = c; }
int priceCents() { return priceCents; }
}
System.out.println(Plan.PRO.priceCents());999
π₯What If?
Think Beyond the Expected
Why is an enum the recommended way to implement a singleton?
Enum singletons are serialization-safe and reflection-proof by construction β the JVM guarantees a single instance, unlike a private-constructor class that can be broken via reflection or deserialization.
πReal World
Order states modeled as an enum with an abstract `next()` method replace sprawling switch statements and make illegal transitions impossible to represent.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βPersisting enum ordinal() (breaks when order changes)
- βUsing int/String constants instead of enums
- βGiant switch statements instead of per-constant behavior
β Best Practices
- βPersist enums by name, never ordinal
- βUse EnumMap/EnumSet for enum-keyed collections
- βPut behavior in the enum to kill switch statements
πFollow-up Questions
- 1What are EnumSet/EnumMap and why are they fast?
- 2How do you persist enums in JPA safely (name vs ordinal)?
- 3How does an enum implement a state machine?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: OOP (Core Java) Interview question: "Why prefer enums over int/String constants, and how do you put behavior in an enum?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.