Nearby lessons

101 of 125

Java - Records

📌 What You Will Learn
  • 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.

Example01
Loading editor…

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).

In simple words: A record is a class that writes all the boring boilerplate for you. You just list the fields in parentheses, and Java creates the constructor, accessors, toString, equals, and hashCode automatically.
Example02
Loading editor…

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).

In simple words: A sealed class is a family of classes with a fixed member list. Only the classes named in permits can extend it, so the compiler always knows every possible subclass.
Example03
Loading editor…
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.