Records In Java

Doğukan HAN
2 min readAug 28, 2022

--

Records were introduced in java 14 and are very popular these days. Records are just immutable classes that help you to write less and do more. It’s a robust way to create immutable classes.

An example of the simplest Record:

record Student(String firstName, String lastName, int age) {}
  1. It’s a final class with the name of Student.
  2. It has a constructer that takes three arguments( firstName, lastName, age)
  3. It has three instance variables( firstName, lastName, age)
  4. It has three getter methods ( firstName(), lastName(), age())

As you can see, you can create these using regular java classes. So the equal java class is like this:

public final class Student{
private final String firstName;
private final String lastName;
private final int age;

Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

public String firstName() {
return firstName;
}

public String lastName() {
return lastName;
}

public int age() {
return age;
}
}

With records, you can implement interfaces, but you can’t extends classes or another records(because they are final).

public record Student(String firstName, String lastName, int age) implements Serializable {}

You can define constructors, but they are additional, and you must call the first constructor with using this() keyword.

public record Student(String firstName, String lastName, int age){
public Student() {
this("Test","Test",30);
}
}

A Compact Constructor is a way of modifying the default constructor. You can validate arguments or change them before setting them. Although, you can’t access any instance variable in the block.

public record Student(String firstName, String lastName, int age) {
public Student {

firstName = firstName.trim();
lastName = lastName.trim();

if (age < 18 || age > 100) {
throw new IllegalArgumentException("Age cannot be bigger than 100 or lower than 18");
}
}
}

You can define static variables, but defining instance variables will produce compile error.

public record Student(String firstName, String lastName, int age) {
static int count; // no problem
int Id; // compile error!

You can define additional methods or change getter methods generated by Record. As you know, the variables are final. Thence, you can’t assign anything to them.

public record Student(String firstName, String lastName, int age) {
public String fullName(){
return this.firstName + " " + this.lastName;
}

public String firstName(){
return this.firstName;
}

You can also use Generics with Records.

public record Student<T extends Person> (String firstName, String lastName, int age, T teacher){

Thank you for reading this. You can access more detailed information in oracle’s website

https://docs.oracle.com/en/java/javase/17/language/records.html

--

--