BackendBench
Coffee
Spot the Bug #106

Accents that depend on the server

A medium 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.

mediumString handlingbuggy line: 6

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

What is wrong

new String(byte[]) decodes with the platform default charset. On a machine whose default is ISO-8859-1 or Windows-1252, the two bytes for the accented letter become two odd characters. The same code gives different results on different servers (Java 18 made UTF-8 the default).

The fix

String text = new String(bytes, StandardCharsets.UTF_8);

How to avoid it next time

Always name the charset when converting between bytes and strings.

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

๐Ÿž Play today's puzzleAll 132 bugsโ† #105#107 โ†’

Frequently asked questions

What is the bug in "Accents that depend on the server"?

new String(byte[]) decodes with the platform default charset. On a machine whose default is ISO-8859-1 or Windows-1252, the two bytes for the accented letter become two odd characters. The same code gives different results on different servers (Java 18 made UTF-8 the default). The faulty line is line 6: String text = new String(bytes);

How do I fix it?

Replace it with: String text = new String(bytes, StandardCharsets.UTF_8);. Always name the charset when converting between bytes and strings.

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.

More tools you might need