Java Records
A record is a class for carrying data, and the compiler writes its common methods. The previous lesson wrote equals and hashCode by hand for a data class.
A record replaces the hand-written class
One header names the data. The printed form shows every field.
public class Main {
public static void main(String[] args) {
Student ana = new Student("Ana", 92);
System.out.println(ana);
}
}
record Student(String name, int score) {}Accessors carry the component names
Each component gets an accessor with the same name. No get prefix appears.
public class Main {
public static void main(String[] args) {
Student ana = new Student("Ana", 92);
System.out.println(ana.name());
System.out.println(ana.score());
}
}
record Student(String name, int score) {}Equals and hashCode come for free
Two records with the same data compare equal. Their hash codes match too.
public class Main {
public static void main(String[] args) {
Student first = new Student("Ana", 92);
Student second = new Student("Ana", 92);
System.out.println(first.equals(second));
System.out.println(first.hashCode() == second.hashCode());
}
}
record Student(String name, int score) {}Example
public class Main {
public static void main(String[] args) {
Student ana = new Student("Ana", 92);
Student ben = new Student("Ben", 85);
System.out.println(ana);
System.out.println(ben);
System.out.println(ana.equals(ben));
}
}
record Student(String name, int score) {}Key points
- A record declares its data as components in its header.
- The compiler writes a constructor, accessors, equals, hashCode and toString for a record.
- A record prints every component by name and value.
- Two records are equal when every component matches.
- A record field cannot change after the record is made.
In this example, two records print in the same field form, and the different scores make equals answer false.
Note
A record suits plain data, not behaviour or changing state.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does printing a record Student with name Ana and score 92 show?