One becomes one point zero
A hard Java puzzle in the boxing and generics 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 3. Play this one as a puzzle without the answer.
What is wrong
When the branches of ?: are an int and a double, binary numeric promotion makes the result a double, so the program prints 1.0 even though the chosen branch is the int 1. The declared type Object does not change that.
The fix
How to avoid it next time
Keep the two branches of a ternary the same type, or cast both to a common reference type.
Want the background? Read Loops, labels and do-while in the Java concepts library.
About boxing and generics
Autoboxing, overload resolution and generics erasure change what a line of code means. The Integer cache, List.remove(int) versus remove(Object) and raw types all behave in ways that surprise careful readers.
In code review: Check the static types involved. When an overloaded method takes either a primitive or an object, work out which one the compiler picks.
More puzzles in this family
Frequently asked questions
What is the bug in "One becomes one point zero"?
When the branches of ?: are an int and a double, binary numeric promotion makes the result a double, so the program prints 1.0 even though the chosen branch is the int 1. The declared type Object does not change that. The faulty line is line 3: Object shown = wholeNumber ? 1 : 2.0;
How do I fix it?
Replace it with: Object shown = wholeNumber ? (Object) 1 : (Object) 2.0;. Keep the two branches of a ternary the same type, or cast both to a common reference type.
How do I catch boxing and generics in code review?
Check the static types involved. When an overloaded method takes either a primitive or an object, work out which one the compiler picks.
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.