AI Hints
Home›Java Tutorial›Interfaces, Records and Enums
Java · Lesson 80 of 120

Records

Tiny data classes.

⏱ 2 min read▶ Video at 1:41:01🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Lots of classes just hold some data. A point, a person, an order. Writing fields, a constructor, getters, to string, and equals, takes a lot of lines. A record does it all, in one.

  • Classes that hold data
  • So much boilerplate
  • A record, in one line

Point.java

Record Point, with x and y. That one line gives us private final fields, a constructor, getters, to string, and equals. We can still add our own methods, like distance from origin.

Main.javajava
public record Point(int x, int y) {
    public double distanceFromOrigin() {
        return Math.sqrt(x * x + y * y);
    }
}

Using a record

New Point creates one, as usual. Printing it shows the values, automatically. The getters are called x, and y, without the word get. Two records with the same values are equal. Run it. Point three, four. A distance of five. And equal, true.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println("x is " + p.x() + ", y is " + p.y());
        System.out.println("Distance: " + p.distanceFromOrigin());
        Point q = new Point(3, 4);
        System.out.println("Equal? " + p.equals(q));
    }
}
Output
Point[x=3, y=4]
x is 3, y is 4
Distance: 5.0
Equal? true
Also uses Point.java
public record Point(int x, int y) {
    public double distanceFromOrigin() {
        return Math.sqrt(x * x + y * y);
    }
}

What a record gives you

Records are immutable, which means their values can't change after creation. That makes them safe to share. Use them for data carriers, like results, messages, and settings.

keyvalue
Fieldsprivate final
Methodsx(), y(), toString, equals
Immutablevalues never change
Use forplain data

Summary

A record is a one line data class, with a constructor, getters, to string, and equals for free. Its values can't change. Next, enums.

Key takeaways
  • record Point(int x, int y)
  • p.x(), not getX()
  • Immutable
Next up: Enums — a fixed set of values