1. Concept library
  2. Java & Spring Boot
  3. Module 1: Modern Java essentials

Concept

Records and var

A record declares an immutable data class in one line, with constructor, accessors, equals, hashCode and toString generated. var lets the compiler infer a local variable's type from its initialiser.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a record generates and what it cannot do
  2. Write a record for a value and use its accessors and equals
  3. Spot the record used for state that changes, and model it as a class

In practice

A few lines that show Records and var doing its job.

Java
public record Money(String currency, long cents) {
    public Money {
        if (cents < 0) throw new IllegalArgumentException("negative amount");
    }
    public Money plus(Money other) {
        return new Money(currency, cents + other.cents);
    }
}

var total = new Money("USD", 1999).plus(new Money("USD", 1));
System.out.println(total);   // Money[currency=USD, cents=2000]

The common mistake

Watch for

Using a record for something that must change over time, then adding setters through workarounds. A record's fields are final; model mutable state with a class.

How it stays learned

Once a session shows you understand Records and var, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Records and var.