Java from zero: a record keeps the cents
A record is a small object with fields the constructor sets. Money holds cents. Adding three lattes of 450 prints 1350.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
A record is a class with the constructor, the fields, and the readers written for you. Money has one component, cents. add returns a new Money. It does not change the one you already hold.
A record is a value you do not mutate#
A record gives you a constructor, accessors, and equality from the components you name. Money has one component, cents. add does not change this. It returns a new Money whose cents are the sum. addExact throws if the sum does not fit in an int, so a silent wrap to a negative price cannot happen. Three lattes are 450 + 450 + 450. The original latte is still 450 after the expression, because each call built a different object.
- latte450
- add latte900
- add latte1350
public class Main {
record Money(int cents) {
Money add(Money other) {
return new Money(Math.addExact(this.cents, other.cents));
}
}
public static void main(String[] args) {
Money latte = new Money(450);
Money total = latte.add(latte).add(latte);
System.out.println(total.cents());
}
}
1350
add returns a new object#
latte is 450 cents. latte.add(latte) is a new Money of 900. Calling add(latte) on that result makes 1350. latte.cents() is still 450. The original object did not change. That is easier to follow than a method that updates a field in place, because each name keeps the value you gave it.
Math.addExact throws ArithmeticException if the sum does not fit in an int, instead of wrapping around to a negative price. Three lattes are nowhere near that limit. The call is there so a huge sum fails loudly.
Format at the edge#
1350 cents is $13.50 when you show it to a person. Divide by 100 only in the line that formats the receipt. The object keeps the int. The next lesson lets a function accept any object that has the one method it calls.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.