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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
