Skip to content
Ameen Abozaid
In reviewJNR-001-L02

Records

  • Lesson 2 of 8
  • 11 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

replace a boilerplate data class with a record.

Planned topics

  • A record is a short way to write an immutable data class.
  • Java generates the constructor, getters (like name()), equals, hashCode, and toString.
  • A compact constructor has no parameter list. Use it to validate the values.
  • Records are shallow: if a component is a mutable list, copy it with List.copyOf.
  • Records cannot have setters or extra instance fields.
Draft outline details

Demonstration

java
public record Money(long cents, String currency) {
    public Money {
        if (cents < 0) throw new IllegalArgumentException("negative");
        currency = currency.toUpperCase();
    }
}

Check your understanding

What does a compact constructor do?

Show answer

It runs checks or cleans values before the fields are set.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.