The first letter that is half an emoji
A hard Java puzzle in the string handling 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
Java strings are UTF-16. An emoji outside the basic plane takes two chars (a surrogate pair), so charAt(0) returns half of it, which prints as a question mark. length and substring count chars, not user-visible characters.
The fix
How to avoid it next time
Use code points for characters beyond the basic plane, and BreakIterator for graphemes such as flags.
Want the background? Read Characters, Unicode and encodings in the Java concepts library.
About string handling
Strings are immutable, split and replaceAll take regular expressions, and character encodings default to whatever the platform says. Small misunderstandings produce wrong output rather than errors.
In code review: Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.
More puzzles in this family
Frequently asked questions
What is the bug in "The first letter that is half an emoji"?
Java strings are UTF-16. An emoji outside the basic plane takes two chars (a surrogate pair), so charAt(0) returns half of it, which prints as a question mark. length and substring count chars, not user-visible characters. The faulty line is line 3: return String.valueOf(name.charAt(0));
How do I fix it?
Replace it with: int cp = name.codePointAt(0); return new String(Character.toChars(cp));. Use code points for characters beyond the basic plane, and BreakIterator for graphemes such as flags.
How do I catch string handling in code review?
Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.
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.