Adding two letters gives a number
A easy 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 7. Play this one as a puzzle without the answer.
What is wrong
Arithmetic on two char values promotes them to int, so the first line prints 195 (97 + 98) rather than ab. Only when a String is involved does + concatenate.
The fix
How to avoid it next time
Start a concatenation with a String, or use StringBuilder and String.valueOf, when combining characters.
Want the background? Read Primitive types and floating point 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 "Adding two letters gives a number"?
Arithmetic on two char values promotes them to int, so the first line prints 195 (97 + 98) rather than ab. Only when a String is involved does + concatenate. The faulty line is line 7: show("first", 'a' + 'b');
How do I fix it?
Replace it with: System.out.println("" + 'a' + 'b'); // or String.valueOf('a') + 'b'. Start a concatenation with a String, or use StringBuilder and String.valueOf, when combining characters.
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.