The command that never matches
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.
Highlighted: line 4. Play this one as a puzzle without the answer.
What is wrong
== compares references, and a string read at runtime is a different object than the literal "stop", even with the same characters. The comparison is false, so the loop never stops. It can appear to work when both sides are literals because those are interned.
The fix
How to avoid it next time
Compare strings with equals, and put the literal first so a null value cannot throw.
Want the background? Read Strings: immutability, equality, common methods 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
Frequently asked questions
What is the bug in "The command that never matches"?
== compares references, and a string read at runtime is a different object than the literal "stop", even with the same characters. The comparison is false, so the loop never stops. It can appear to work when both sides are literals because those are interned. The faulty line is line 4: if (command == "stop") {
How do I fix it?
Replace it with: if ("stop".equals(command)) {. Compare strings with equals, and put the literal first so a null value cannot throw.
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.