Quick revision
The short answer
equals checks identity first, then uses instanceof with a pattern variable to reject other types and null, and compares cents with == and currency with equals. hashCode combines the same two fields, either with Objects.hash(cents, currency) or, without boxing, 31 * Long.hashCode(cents) + currency.hashCode(). Because Money is final, instanceof is safe, and a record Money(long cents, String currency) would generate equivalent methods for us.
What to remember
In this answer, we wrote equals and hashCode for a final Money class. equals overrides Object.equals, short-circuits on identity, uses an instanceof pattern to reject null and other types, and compares cents with == and currency with equals. hashCode uses the same two fields, through Objects.hash or 31 * Long.hashCode(cents) + currency.hashCode(). We saw that final is what makes instanceof safe, and that a record generates equivalent methods for us.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
equals checks identity first, then uses instanceof with a pattern variable to reject other types and null, and compares cents with == and currency with equals. hashCode combines the same two fields, either with Objects.hash(cents, currency) or, without boxing, 31 * Long.hashCode(cents) + currency.hashCode(). Because Money is final, instanceof is safe, and a record Money(long cents, String currency) would generate equivalent methods for us.
Why this question is asked
Money is the classic value class: two amounts of 1500 cents in euros are the same amount, no matter which object holds them. Writing equals and hashCode for it looks trivial, yet it is easy to get one detail wrong, such as comparing strings with ==, overloading instead of overriding, or using different fields in the two methods. Interviewers ask for it as a quick coding exercise because every line has a reason. In this answer, we will look at a broken first attempt, write a correct equals line by line, choose a hashCode, see why the class being final matters, and finish with the record that does all of it for us.
1What We Need From Money
Money has two fields: cents, a long holding the amount in the smallest unit, and currency, a String such as "EUR". Both are final, so a Money object never changes after it is built. We want two Money objects to be equal exactly when both fields are equal, and we want Money to work as a key in a HashMap or an element of a HashSet.
That means overriding equals, to compare contents instead of identity, and hashCode, so that equal amounts land in the same hash bucket. One more detail helps everything that follows: the constructor should refuse a null currency, so the methods can rely on it.
2A First Attempt That Looks Right but Is Not
Here is a version that compiles and even passes a quick test, but contains two classic mistakes.
The first mistake is the parameter type. equals(Money) does not override Object.equals(Object); it adds a second method. Collections call equals(Object), so they never see ours. The @Override annotation would have turned this into a compile error, which is why we always write it. The second mistake is ==, which compares String references, not their characters. It works for string literals only because the JVM shares identical literals, and fails as soon as a currency comes from a database or a JSON request.
3Writing equals Line by Line
Here is the correct version. Each line has a job.
- Same reference?YesReturn trueNoCheck the type
- Is o a Money (and not null)?YesCompare the fieldsNoReturn false
- cents == m.cents and currency.equals(m.currency)?YesReturn trueNoReturn false
3 steps in order. Play them, or step through them one at a time.
Cheap checks first; the field comparison only runs for another Money.
The identity check is a shortcut: an object is always equal to itself, and comparing references is the cheapest test. The instanceof pattern, available since Java 16, does two things at once. It returns false for null, which satisfies the rule that x.equals(null) is false, and it gives us a typed variable m without a cast. Finally we compare the fields: cents is a primitive, so == is right; currency is an object, so we use equals. Because the constructor rejected null, currency.equals cannot throw; if nulls were allowed, Objects.equals(currency, m.currency) would handle them.
4Writing hashCode From the Same Fields
hashCode must give equal Money objects equal hash codes, so it must use the same fields as equals, and no others. There are two common ways to write it.
Objects.hash is the easiest to read and is correct, but it takes varargs, so each call boxes the long and allocates an array. That rarely matters, but Money may be a key in hot code. The hand-written version uses Long.hashCode, which folds the 64-bit value into 32 bits by mixing its high and low halves, and multiplies by 31, an odd prime, so that the order of fields affects the result and similar values spread out. Notice that if we added a field to equals later, we would have to add it here too. Using different fields in the two methods is the most common way to break the contract.
5Why final Makes instanceof Safe
instanceof Money would also accept a subclass of Money. If someone could write class TaxedMoney extends Money with an extra field, Money.equals would say a Money equals a TaxedMoney, while TaxedMoney.equals might say the opposite, breaking symmetry. Because Money is final, no subclass can exist, and instanceof is exactly the same as checking the class.
For a class that is not final, we have two choices. We can compare getClass() == o.getClass(), which keeps symmetry but means no subclass instance is ever equal to a parent instance. Or we can declare equals and hashCode final in the parent, so subclasses cannot change the meaning of equality. For value classes such as Money, making the class final is the simplest answer.
6The Record That Does It for Us
Since Java 16, a record generates exactly this pair of methods from its components, along with the constructor, accessors and toString. A compact constructor keeps the null check.
Records are implicitly final, their fields are final, and their equals and hashCode always use every component, so they cannot drift apart. The exact hash values a record produces are not specified, so code should never depend on them. For value types like Money, a record is the default choice today, and hand-written methods are for the rare case where equality must ignore a component.
7Follow-up questions
Should currency be a String or java.util.Currency?
Currency is better in real code: it validates the ISO code and its instances are shared, one per currency, so equality and hashing are simple. The equals and hashCode logic stays the same either way; only the field's type changes.
Why not compare amounts as BigDecimal values instead of cents?
That is a valid design, but then equals must decide whether 1.5 and 1.50 are the same amount. BigDecimal.equals says no, because the scale differs, while compareTo says yes. Storing cents as a long avoids that question entirely, which is one reason many systems use it.
How would you test these methods?
Test equal and unequal pairs for each field, null, another type and the hash code of equal objects. A library such as EqualsVerifier checks the whole contract, including symmetry, transitivity and the consistency of hashCode with equals, in a single test line.
8Conclusion
In this answer, we wrote equals and hashCode for a final Money class. equals overrides Object.equals, short-circuits on identity, uses an instanceof pattern to reject null and other types, and compares cents with == and currency with equals. hashCode uses the same two fields, through Objects.hash or 31 * Long.hashCode(cents) + currency.hashCode(). We saw that final is what makes instanceof safe, and that a record generates equivalent methods for us.
Open with
I would write equals as an override of equals(Object), with @Override so the compiler catches an accidental overload. First, if this == o, return true; that is the cheap reflexive case.
Then, if they want more
Then, if !(o instanceof Money m), return false; the pattern handles both null and other types and gives me a typed variable. Then return cents == m.cents && currency.equals(m.currency): == for the primitive long, equals for the String, never == on strings. I make the constructor reject a null currency so that call is safe; otherwise I would use Objects.equals.
For hashCode I must use exactly the same fields: Objects.hash(cents, currency) is the simplest, or 31 * Long.hashCode(cents) + currency.hashCode() if I want to avoid boxing in hot code.
The class being final is what makes instanceof safe, because no subclass can add a field and break symmetry; for a non-final class I would think about getClass() comparison or making equals final.
And honestly, today I would just write record Money(long cents, String currency) with a compact constructor for the null check, because the record generates equivalent equals, hashCode and toString and they can never drift apart.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a correct equals and hashCode for final class Money { private final long cents...": https://scrivio-interview-library.netlify.app/java/object-contracts/8f1e81e905/