Records, enums & Optional: interview questions & scenarios
These are the records, enums and Optional questions I ask most in Java backend interviews. They look like warm-ups, but each one has a follow-up that separates people who use the feature from people who understand what the compiler and the JVM do with it.
Read each question, say your answer out loud first, then open the model answer. The deeper explanations live in this topic's lessons: Records in Java, A guide to Java enums and A guide to Java Optional.
What exactly does the compiler generate for record Point(int x, int y) {}?
Tests record members, java.lang.Record, accessors
Show answerHide answer
Model answer
A final class that extends java.lang.Record, with:
- two
private final intfields,xandy; - a canonical constructor
Point(int x, int y)that assigns them; - public accessors
x()andy()(notgetX()); - value-based
equals,hashCodeandtoString, sonew Point(1, 2).equals(new Point(1, 2))istrueand it printsPoint[x=1, y=2].
Because it already extends Record and is final, a record can't extend another class or be extended. It can implement interfaces and declare static members and instance methods.
How I’d say it in the interview
"A final class extending Record, with private final fields, a canonical constructor, accessors named after the components, and equals, hashCode and toString based on all components. That's why it can't extend anything else."
Signals depth
Mentioning that equals, hashCode and toString are bootstrapped through invokedynamic to ObjectMethods, and that primitive components follow the generated comparison rules, including the Double.compare style behavior for floating point values.
Red flags
"It generates getters and setters." Records have no setters, and the accessors aren't getX().
Follow-ups interviewers ask next
What if I declare
private int z;inside the record body?It doesn't compile: records can't declare instance fields. All state must be in the header, otherwise the generated
equalsand the constructor would not describe the whole object. Astaticfield is fine.What if I need a derived value like
distanceFromOrigin?Add an instance method that computes it:
double distance() { return Math.hypot(x, y); }. If it is expensive and you want to cache it, a record is the wrong tool; use a normal class.
Where would you put validation for a record, and what are the constructor rules?
Tests compact constructor, canonical constructor rules
Show answerHide answer
Model answer
Use a compact constructor when you are validating or normalising the record components:
public record Money(long amountMinor, String currency) {
public Money {
if (amountMinor < 0) throw new IllegalArgumentException("negative amount");
Objects.requireNonNull(currency, "currency");
currency = currency.toUpperCase(Locale.ROOT);
}
}
The compact constructor has no parameter list. You can reassign the parameters, but you cannot assign this.currency = ...; the compiler writes the field assignments after your constructor body. Every other constructor must start with this(...), so all paths go through the canonical constructor.
How I’d say it in the interview
"I put validation in the compact constructor. I validate and normalise the parameters there, the compiler assigns the fields afterwards, and every extra constructor has to delegate with this(...)."
Signals depth
Adding that deserialization of a Serializable record also goes through the canonical constructor, so validation protects against crafted byte streams too.
Red flags
Putting validation in the accessor, or saying "records can't have constructors".
Follow-ups interviewers ask next
What if I want a private constructor and a static factory, like
Money.of(...)?You can add the factory, but you can't hide the canonical constructor of a
publicrecord: it must be at least as accessible as the record. If you need that control, use a regular final class.What if the compact constructor forgets to check
currencyfor null?Then the record can still be created with
currency == null, and the generated methods will tolerate it in ways your domain may not. Records give you a good validation point, not automatic domain validation.
Your cart cache started returning stale totals after a rollout that changed Cart to a record. Walk me through it.
Tests shallow immutability, defensive copies, hash-based collections
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
What does javac generate for an enum, and why is == safe for comparing enums?
Tests Enum class, static final constants, class init
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Your payments table started mapping old PAID orders to PAYMENT_PENDING after an enum change. What happened?
Tests ordinal persistence, JPA @Enumerated, data migration
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
What does this print, and how would you fix it?
Tests orElse eager evaluation, orElseGet
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Should I use Optional for fields and method parameters?
Tests Optional design intent, Serializable, API design
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Rewrite this with Optional, and tell me when you would use map versus flatMap.
Tests map, flatMap, null chains
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Your user API started throwing NullPointerException from findUser(id).map(...) after a repository refactor. Walk me through it.
Tests Optional return contract, null Optional, repository APIs
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Your Hibernate service started failing at startup after someone converted OrderEntity into a record. What would you tell the team?
Tests records vs JPA requirements, projections
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why is EnumSet faster than a HashSet of enum values?
Tests bit vector, EnumMap, memory
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
When would you model something as an enum, and when as a sealed interface of records?
Tests enums vs sealed types, pattern matching, exhaustiveness
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why does Effective Java call a single-element enum the best singleton?
Tests enum singleton, serialization, reflection, class init
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Why are a record's equals, hashCode and toString implemented with invokedynamic?
Tests invokedynamic, ObjectMethods, bytecode
Model answer, how to say it, 2 follow-ups: unlock with the Java Pass
Premium question set
Keep reading with the Java Pass
The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.
From ₹199 · one-time payment · No auto-renewal