Java 14 introduced a new way to create classes called Records. In this tutorial, we will learn:
Recommended Reading: Java 14 Features
One of the common complaints with Java has been its verbosity. If you have to create a simple POJO class, it requires the following boiler-plate code.
This verbosity is one of the reasons for high interest in Kotlin and Project Lombok.
In fact, the sheer frustration of writing these generic methods each and every time lead to the shortcuts to create them in Java IDEs such as Eclipse and IntelliJ IDEA.
Here is the screenshot showing Eclipse IDE option to generate the ceremonial methods for a class.
Java Records are meant to remove this verbosity by providing a compact structure to create the POJO classes.
Java Records is a preview feature, which is developed under JEP 359. So, you need two things to create Records in your Java projects.
You can enable Java 14 preview features in the command line using the --enable-preview -source 14
option.
Let’s say I want to create a Employee model class. It will look something like the following code.
Phew, that’s 70+ lines of auto-generated code. Now let’s see how to create an Employee Record class, which essentially provides the same features.
Wow, this can’t go any shorter than this. I am already loving Record classes.
Now, let’s use the javap
command to figure out what is happening behind the scene when a Record is compiled.
If you want more internal details, run the javap command with -v option.
java.lang.Record
class.Let’s look at a simple example of using our EmpRecord class.
Output:
The Record object works in the same way as any model class, data object, etc.
Sometimes, we want to have some validations or logging in our constructor. For example, employee id and salary should not be negative. The default constructor won’t have this validation. We can create a compact constructor in the record class. The code of this constructor will be placed at the start of the auto-generated constructor.
If we create an EmpRecord like the following code:
We will get runtime exception as:
Yes, we can create method in records.
But, records are meant to be data carriers. We should avoid having utility methods in a record class. For example, the above method can be created in a utility class.
If you think that having a method is must for your Record class, think carefully if you really need a Record class?
Java Records are a welcome addition to the core programming features. You can think of it as a “named tuple”. It’s meant to create a data carrier object with compact structure, avoiding all the boiler-plate code.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.