Bits of Java – Episode 26: What’s new in Java?

We started this blog series with Java 11. This is the most recent LTS (long-term support) version of Java so far and it was released in September 2018.

Since then, however, a lot of other versions have been released, and currently we are at Java 15, so I think it is worth mentioning some of the newest and coolest features that have been introduced.

Today we will start with records!

Records are a very compact way of defining an immutable object in Java. Before their introduction, if you needed to define an immutable object, you would have probably done something like this:

where the field name is defined as private final, and its value is set using the constructor. You can, then, only retrieve such value, but not set it again.

Records allow you to obtain the same result, but with a much more concise code. You just need to write something like this:

and you are done!

Let's have a look at what's going on here. First, we can see that, instead of the keyword class a new one has been introduced, record. Then the parameter we want to be taken as private final instance field is passed as argument.

Under the hood, the private final fields we pass as argument are added for us, together with a public constructor that takes as input parameters the values of such fields.

Also the public getter methods for each of the parameters are automatically added, with the same name as the parameters. So, in our case we could call:

This covers the basic concepts behind records in Java!

I hope you found this post useful! If so, stay tuned for the next episode of the series, where we will look into more new features of Java!