Complete Java Records Tutorial |Video upload date:  · Duration: PT20M14S  · Language: EN

Compact guide to Java records covering syntax constructors validation and use cases for immutable data classes

Why records are the lazy programmer's dream

If you have ever written a plain old data class and then stared at equals hashCode and toString like they were a bad smell you will love Java records. Records give you immutable data carriers with minimal boilerplate and clear intent. They are perfect for small domain models that hold state but do not do heavy lifting.

Define a record

Declaring a record is almost criminally simple. The compiler generates a canonical constructor component accessors and implementations of equals hashCode and toString for you.

// simple 2D point
record Point(int x int y) {
}

That one line creates a constructor Point(int x int y) and two accessors x() and y() without copying and pasting boilerplate. Yes it feels like cheating and yes you should use it.

When to prefer records

  • Simple immutable data carriers
  • DTOs for APIs where mutability is a bug not a feature
  • Value objects with well defined equality based on components

Constructors and validation

Records provide a canonical constructor and you can add a compact constructor to validate or normalize input without repeating types. Compact constructors let you keep the declaration tidy while enforcing invariants.

// validation with a compact constructor
record Person(String name int age) {
    Person {
        if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
        if (age < 0) throw new IllegalArgumentException("age must be non negative");
    }

    // helper method for derived values
    String greeting() {
        return "Hello " + name;
    }
}

Use compact constructors to reject bad data up front. If your object needs lots of mutable state or complex lifecycle rules pick a normal class instead.

Accessors equals hashCode and toString

Each record component gets a public accessor with the same name as the component. The generated equals and hashCode methods use component order which makes equality predictable. The generated toString is concise and useful for debugging.

Point p = new Point(1 2);
int x = p.x();
String s = p.toString();

Custom methods and keeping immutability

Records are more flexible than they look. You can add static factories convenience methods and derived value helpers. Just avoid adding mutable instance fields if you care about immutability. Side effects and hidden state defeat the point of using a record.

Pattern matching and deconstruction

Records pair nicely with pattern matching for structure based code. You can deconstruct a record in an instance of check or in a switch to match by components and bind names directly.

// pattern matching with record deconstruction
Object o = new Point(3 4);
if (o instanceof Point(int x int y)) {
    System.out.println("x plus y is " + (x + y));
}

// switch style matching for clearer branching
switch (o) {
    case Point(int x int y) -> System.out.println("point " + x + "," + y);
    default -> System.out.println("not a point");
}

Pattern matching features evolve across Java releases so check your target JDK version before using the newest syntax in production code.

Best practices cheat sheet

  • Prefer records for simple immutable value objects and DTOs
  • Use compact constructors for validation and normalization
  • Avoid mutable instance fields in records
  • Rely on generated equals hashCode and toString unless you have a good reason not to
  • Use pattern matching and deconstruction to write clearer branching code

Final thoughts

Records reduce boilerplate and make intent explicit. They are not a silver bullet for every design but for many simple domain models they are the right tool. Embrace them for immutable data and keep business logic in classes that do interesting work. Your future self will thank you or at least curse you less often.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.