Quiz: Java Records: What a record Is and How to Use It

Total: 8 questions

1. 

What is a record in Java, and what does the compiler generate for it?

A record is a special kind of class for immutable data carriers, a standard language feature since Java 16 (JEP 395; a preview in Java 14 and 15). You list the components in the header, and the compiler creates the rest. For record Point(int x, int y) it generates:

  • private final fields x and y;
  • public accessors x() and y() - without the get prefix;
  • the canonical constructor Point(int x, int y);
  • equals() and hashCode() over all components, and toString() like Point[x=1, y=2].

A record is implicitly final and implicitly extends java.lang.Record, so it cannot extend another class. You cannot extend Record by hand either: class P extends Record fails with classes cannot directly extend Record.

2. 

What rules apply to record components and explicitly declared accessors?

Each component gets a private final field and a public accessor with the same name: for title it is title(), and a call to getTitle() does not compile.

You can declare an accessor explicitly (for example, to return a copy of an array), but it has to match the generated one:

  • be public - otherwise invalid accessor method (accessor method must be public);
  • return exactly the same type - public long x() for int x does not compile;
  • take no parameters and declare no throws;
  • @Override is allowed on it.

A component cannot be named after a no-argument method of Object: clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait - for record R(int hashCode) javac reports illegal record component name hashCode. The last component can be varargs, a record can be generic, and record Empty() { } with no components compiles too.

3. 

How does the canonical constructor of a record differ from the compact constructor, and what rules apply to each?

The canonical constructor is the constructor whose parameters match the components in order, type and name. If you do not declare it, the compiler generates it. In its full form it looks like an ordinary constructor, and every field must be assigned exactly once. Rules: parameter names match the component names, access is not more restrictive than the record (a public record needs a public one), no throws, no this(...) or super(...) call.

The compact constructor is a shorthand form of the same canonical constructor: no parameter list and no field assignments.

public record Email(String value) {
    public Email {
        Objects.requireNonNull(value, "value");
        value = value.strip().toLowerCase();   // reassign the parameter, not the field
    }                                          // implicitly: this.value = value;
}

Its body runs before the assignments the compiler appends at the end, which makes it the place to validate and normalize arguments. Not allowed: assigning a field (this.value = value gives cannot assign a value to final variable), return (compact constructor must not have return statements), and declaring both the compact and the full form (constructor ... is already defined). In the full form return is allowed.

4. 

Can a record declare extra constructors, and what rules apply to them?

Yes, but every non-canonical constructor must call another constructor through this(...):

public record Person(String name, int age) {
    public Person(String name) {
        this(name, 0);
    }
}

Without this(...) you get constructor is not canonical, so it must invoke another constructor of class Person. Every chain ends in the canonical constructor, so its checks cannot be bypassed.

Before Java 25 the this(...) call had to be the first statement; Java 25 flexible constructor bodies (JEP 513) allow code before it, as long as that code does not touch the object under construction. A static factory method (Point.of(x, y)) and a static constant (Point.ORIGIN) are often handier than extra constructors - static members are allowed in records.

5. 

How do the generated equals(), hashCode() and toString() work in a record?

equals() treats records as equal when they belong to the same record class and all components are pairwise equal; hashCode() is derived from the hash codes of all components; toString() prints the name and the components: Point[x=1, y=2]. The exact hashing algorithm and toString() format are not specified.

  • Primitives are compared with the wrapper compare(): for double, NaN equals NaN and 0.0 does not equal -0.0.
  • References are compared with Objects.equals(): null-safe, lists by content.
  • Arrays are also compared with Objects.equals(), that is, by reference; you need your own equals() with Arrays.equals() or an immutable List.

All three methods read the fields, not the accessors: if the accessor celsius() rounds the value, records with 21.456 and 21.46 are still not equal, and toString() shows 21.456. So normalize data in the compact constructor. You can override the methods as usual - for example toString(), to hide a password from the logs.

6. 

What can and cannot be declared in a record?

Not allowed:

  • extends - a record already extends java.lang.Record ('{' expected), and it is final itself: class S extends R gives cannot inherit from final R;
  • abstract record - modifier abstract not allowed here;
  • instance fields - field declaration must be static;
  • instance initializers - instance initializers not allowed in records;
  • native methods and any method that assigns a field (cannot assign a value to final variable).

Allowed: static fields, blocks and methods, instance methods and main(), implementing interfaces (including sealed ones), nested types, and the redundant final modifier.

The key consequence: a record has no room for a cache or a lazy field - all of the object state must be a component and take part in equals().

7. 

Is a record immutable, and how do you protect it from mutable components?

Only shallowly: the fields are final, but if a component refers to a mutable object (an ArrayList, an array, a Date), its content can be changed from outside. The fix is a defensive copy in the compact constructor:

record Order(String id, List<String> items) {
    Order {
        items = List.copyOf(items);   // unmodifiable copy
    }
}

Now changing the source list does not affect the record, and order.items().add("x") throws UnsupportedOperationException. List.copyOf() throws NullPointerException if the list contains null, and does not copy a list that is already unmodifiable. An array needs copying twice: clone() in the constructor and in an explicit accessor.

8. 

How do records behave in HashMap, HashSet and TreeSet, and what is special about nested and local records?

HashMap and HashSet: records make good keys and elements, because equals() and hashCode() are consistent and depend only on the components. A key can be looked up with a new but equal object, and a composite record key replaces concatenated strings like region + "|" + product. A mutable component is dangerous: after the list inside a key changes, the HashMap entry becomes unreachable, even through the same object.

TreeSet and TreeMap: a record does not implement Comparable automatically, so new TreeSet<>(List.of(new Point(2, 1), new Point(1, 2))) compiles but throws ClassCastException. You need a comparator, such as Comparator.comparingInt(Point::x).thenComparingInt(Point::y), or implements Comparable<Point>.

Nested and local records are implicitly static: a nested record cannot see the instance fields of the outer class, and a local record, unlike a local class, cannot access the local variables of the method (non-static variable ... cannot be referenced from a static context).

Page 1 of 1