Java / Java 21 Interview Questions
What are Java Records and what do they automatically generate?
Records (JEP 395, finalised in Java 16) are a concise syntax for declaring immutable data-carrier classes. A single record declaration replaces a full class with private final fields, a canonical constructor, accessors, equals(), hashCode(), and toString().
// Declaration — the header defines the record's components
public record Person(String name, int age) {}
// Equivalent traditional class (simplified):
// private final String name;
// private final int age;
// public Person(String name, int age) { this.name = name; this.age = age; }
// public String name() { return name; } // accessors, NOT getName()
// public int age() { return age; }
// public boolean equals(Object o) { ... }
// public int hashCode() { ... }
// public String toString() { return "Person[name=" + name + ", age=" + age + "]"; }
Person p = new Person("Alice", 30);
System.out.println(p.name()); // Alice (accessor, not getName)
System.out.println(p); // Person[name=Alice, age=30]
// Compact canonical constructor — validate without repeating assignments
public record Range(int lo, int hi) {
Range { // compact form — no parameter list
if (lo > hi) throw new IllegalArgumentException(lo + " > " + hi);
// assignments lo = lo; hi = hi; happen automatically at end
}
}
// Records CAN have:
// - static fields and methods
// - instance methods (non-component)
// - custom constructors that delegate to canonical
// - implement interfaces
// Records CANNOT:
// - extend any class (implicitly extend java.lang.Record)
// - declare instance fields beyond components
// - be abstractRecords work seamlessly with Java 21 features: they are the natural carrier type for record patterns, they compose well with sealed interfaces for algebraic data types, and their auto-generated equals()/hashCode() make them safe as map keys and set elements.
More Related questions...