Home › Learn › Java › Objects

Records

Lesson 29 of 40. A class that is only data, in one line.

A record is a class for plain data: record Point(int x, int y) {} declares the fields, a constructor taking both, accessors x() and y(), and equals, hashCode, and toString (Point[x=1, y=2]), all generated. Records are immutable: there are no setters, and a "change" is a new record. They are the right tool for values that are just their fields.

A record can still have methods, and a compact constructor record Member(String name, String card) { Member { ... } } runs checks on the fields before they are stored, throwing IllegalArgumentException for bad input.

The library project's Member is a record: a name and a card number, with a method that says whether the name is set.

record Point(int x, int y) {
    double distance() {
        return Math.sqrt(x * x + y * y);
    }
}

Point p = new Point(3, 4);
System.out.println(p.x() + " " + p.distance() + " " + p);   // 3 5.0 Point[x=3, y=4]

Your task

Write record Money(int cents) with methods Money plus(Money other) returning the sum as a new record and String show() returning $<dollars>.<two cent digits>. Then write record Member(String name, String card) with a method boolean hasName() returning whether the name is not empty.

Part of the final project. Member is a library member: a name and a card number. It is saved in this browser and loaded into Project: the library when you get there.

Hint 1

Money plus(Money other) { return new Money(cents + other.cents()); }

Hint 2

String show() { return String.format("$%d.%02d", cents / 100, cents % 100); } and boolean hasName() { return !name.isEmpty(); }

Show the solution
public class Main {
    public static void main(String[] args) {
        Money m = new Money(250);
        System.out.println(m.plus(new Money(75)).show());
    }
}

record Money(int cents) {
    Money plus(Money other) {
        return new Money(cents + other.cents());
    }

    String show() {
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }
}

record Member(String name, String card) {
    boolean hasName() {
        return !name.isEmpty();
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.