BackendBench
Coffee
Spot the Bug #12

Two identical arrays that are not equal

A easy 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.

easyEquality and identitybuggy line: 3

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

What is wrong

Arrays inherit equals from Object, which compares references. Two arrays with the same contents are different objects, so the method returns false unless both parameters refer to the same array.

The fix

return java.util.Arrays.equals(entered, expected);

How to avoid it next time

Use Arrays.equals or Arrays.deepEquals for content comparison, and Arrays.toString when printing.

Want the background? Read Arrays and the Arrays utilities 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โ† #11#13 โ†’

Frequently asked questions

What is the bug in "Two identical arrays that are not equal"?

Arrays inherit equals from Object, which compares references. Two arrays with the same contents are different objects, so the method returns false unless both parameters refer to the same array. The faulty line is line 3: return entered.equals(expected);

How do I fix it?

Replace it with: return java.util.Arrays.equals(entered, expected);. Use Arrays.equals or Arrays.deepEquals for content comparison, and Arrays.toString when printing.

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