Course contents

Records, enums & Optional: interview questions & scenarios

Premium14 questions · 28 what-if follow-ups

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.

Question 1. ConceptWarm-upAsked very often

What exactly does the compiler generate for record Point(int x, int y) {}?

Tests record members, java.lang.Record, accessors

Show answerHide answer2 follow-ups

Model answer

A final class that extends java.lang.Record, with:

  • two private final int fields, x and y;
  • a canonical constructor Point(int x, int y) that assigns them;
  • public accessors x() and y() (not getX());
  • value-based equals, hashCode and toString, so new Point(1, 2).equals(new Point(1, 2)) is true and it prints Point[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

  1. 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 equals and the constructor would not describe the whole object. A static field is fine.

    1. 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.

Question 2. CodingWarm-upAsked very often

Where would you put validation for a record, and what are the constructor rules?

Tests compact constructor, canonical constructor rules

Show answerHide answer2 follow-ups

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

  1. 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 public record: it must be at least as accessible as the record. If you need that control, use a regular final class.

    1. What if the compact constructor forgets to check currency for 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.

Question 3. DebuggingCoreAsked very often

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

Question 4. ConceptWarm-upAsked very often

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

Question 5. DebuggingCoreAsked very often

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

Question 6. What does it print?Warm-upAsked very often

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

Question 7. DesignCoreAsked very often

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

Question 8. CodingCoreCommonly asked

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

Question 9. DebuggingCoreCommonly asked

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

Question 10. ScenarioCoreCommonly asked

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

Question 11. ConceptCoreCommonly asked

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

Question 12. DesignSeniorCommonly asked

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

Question 13. ConceptSeniorSometimes asked

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

Question 14. ConceptSeniorSometimes asked

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

Lessons in Records, enums & Optional