Uppercase that changed nothing
A easy 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 4. Play this one as a puzzle without the answer.
What is wrong
Strings are immutable. toUpperCase returns a new string and leaves the original unchanged. Discarding the result means the output is still "Hello ada".
The fix
How to avoid it next time
Always use the return value of String methods. IDE inspections flag ignored results.
Want the background? Read Strings: immutability, equality, common methods 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 "Uppercase that changed nothing"?
Strings are immutable. toUpperCase returns a new string and leaves the original unchanged. Discarding the result means the output is still "Hello ada". The faulty line is line 4: name.toUpperCase();
How do I fix it?
Replace it with: name = name.toUpperCase();. Always use the return value of String methods. IDE inspections flag ignored results.
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.