In Java, we often create multiple classes, including functional classes such as service or utility classes that perform specific tasks. Additionally, we create classes solely for the purpose of storing or carrying data, a practice demonstrated by the use of record classes in Java 17.
For example:
Table of Contents
When to use Record Classes in Java
When our object is immutable and we don’t intend to change its data, we create such objects primarily for data storage. Let’s explore how to create such a class in Java.
Ouput:

In this code, we’ve created a Student
class to represent student data, ensuring immutability by making fields id
, name
, and college
final. Additionally, we’ve overridden toString()
, equals()
, and hashCode()
methods for better readability and correct comparison of objects. Finally, we’ve tested the class in RecordTest
class by creating instances of Student
and performing some operations like printing details and checking for equality.
In Java 17, with the introduction of the records feature, the Student class can be replaced with a record class. It would look like this:
Output:

- Parameterized Constructors: Record classes internally define parameterized constructors. All variables within a record class are private and final by default, reflecting the immutable nature of records.
- Equals() Method Implementation: By default, a record class implements the equals() method, ensuring proper equality comparison between instances.
- Automatic toString() Method: The toString() method is automatically defined for record instances, facilitating better string representation.
- No Default Constructor: It’s important to note that record classes do not have a default constructor. Attempting to instantiate a record class without parameters, like
Student s = new Student();
, would result in an error. - Inheritance and Interfaces: Record classes cannot extend any other class because they implicitly extend the Record class. However, they can implement interfaces.
- Additional Methods: Methods can be added to record classes. Unlike traditional classes, record classes do not require getter and setter methods for accessing variables. Instead, variables are accessed using the syntax
objectName.varName()
. For example:s.name()
.
Java 21 Features with Examples
Latest Posts:
- Saga Design Pattern in Microservices
- Stop Using Relational Databases for Microservices: Polyglot Persistence Wins
- Top Spring Boot Interview Questions with Answers
- DeepSeek AI Features and Advantages
- High Availability in Spring Boot Microservices
For additional information on Java 17 features, please visit