BackendBench
Coffee
Spot the Bug #114

The digit five that is fifty-three

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.

easyBoxing and genericsbuggy line: 5

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

What is wrong

Adding a char to an int adds its character code: '1' is 49, so the sum of "123" is 150 instead of 6. Characters are numbers underneath, and the compiler converts silently.

The fix

total += digits.charAt(i) - '0'; // or Character.getNumericValue(digits.charAt(i))

How to avoid it next time

Convert digit characters with Character.getNumericValue or by subtracting '0'.

Want the background? Read Characters, Unicode and encodings 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

๐Ÿž Play today's puzzleAll 132 bugsโ† #113#115 โ†’

Frequently asked questions

What is the bug in "The digit five that is fifty-three"?

Adding a char to an int adds its character code: '1' is 49, so the sum of "123" is 150 instead of 6. Characters are numbers underneath, and the compiler converts silently. The faulty line is line 5: total += digits.charAt(i);

How do I fix it?

Replace it with: total += digits.charAt(i) - '0'; // or Character.getNumericValue(digits.charAt(i)). Convert digit characters with Character.getNumericValue or by subtracting '0'.

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.

More tools you might need