Nearby lessons
101 of 125Java - Records
- Switch expressions — now FINAL
- Records — the compact class (preview)
- Pattern matching for instanceof (preview)
- Helpful NullPointerException messages
- Text blocks second preview
Records is a core concept of the Java language. This lesson explains Records — Classes Made Simple (Preview) and Java 17 — Sealed Classes with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Records — Classes Made Simple (Preview)
Writing a simple data class in old Java is very long — fields, constructor, getters, toString, equals, hashCode... Records (previewed here, final in Java 16) do all of that automatically with one line.
Records — Classes Made Simple (Preview)
A record automatically gives you: the constructor, the accessor methods (named like rollNo(), without 'get'), and toString, equals, hashCode. Records are meant for classes that are just data carriers — perfect for DTOs (Data Transfer Objects).
Java 17 — Sealed Classes
A sealed class controls exactly which classes may extend it. It sits between open to everyone (normal) and closed to everyone (final):
Why useful? It makes a closed family of types, so switch statements can cover all cases safely (the compiler knows the full list).
- Switch expressions became FINAL in Java 14.
- Records create data classes with automatic constructor, getters, toString, equals, hashCode.
- Pattern matching for instanceof combines check and cast into one step.
- Helpful NPE messages tell you exactly which value was null.
- Text blocks got a second preview before becoming final in Java 15.
- After Java 14: Java 15-24 added text blocks, records, sealed classes, virtual threads.