BackendBench
Coffee
Spot the Bug #11

Two and two point zero are different

A medium Java puzzle in the equality and identity family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumEquality and identitybuggy line: 5

Highlighted: line 5. Play this one as a puzzle without the answer.

What is wrong

BigDecimal.equals compares both the value and the scale, so 0.00 is not equal to 0. A price coming from a database column with two decimal places will never match ZERO. compareTo ignores scale.

The fix

return price.compareTo(BigDecimal.ZERO) == 0;

How to avoid it next time

Use compareTo for numeric comparison of BigDecimal. In hash-based collections, use stripTrailingZeros or a normalized key.

Want the background? Read BigDecimal and money in the Java concepts library.

About equality and identity

In Java == compares primitive values but only compares references for objects. Strings, boxed numbers and enums behave differently, and a class that overrides equals without hashCode quietly breaks every hash-based collection.

In code review: Whenever you see == between two objects, stop and ask whether identity was really intended. Use equals or Objects.equals, and look for equals and hashCode written as a pair.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #10#12 โ†’

Frequently asked questions

What is the bug in "Two and two point zero are different"?

BigDecimal.equals compares both the value and the scale, so 0.00 is not equal to 0. A price coming from a database column with two decimal places will never match ZERO. compareTo ignores scale. The faulty line is line 5: return price.equals(BigDecimal.ZERO);

How do I fix it?

Replace it with: return price.compareTo(BigDecimal.ZERO) == 0;. Use compareTo for numeric comparison of BigDecimal. In hash-based collections, use stripTrailingZeros or a normalized key.

How do I catch equality and identity in code review?

Whenever you see == between two objects, stop and ask whether identity was really intended. Use equals or Objects.equals, and look for equals and hashCode written as a pair.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need