BackendBench
Coffee
Spot the Bug #104

The version string that splits into 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.

easyString handlingbuggy line: 4

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

What is wrong

split takes a regular expression, and . matches any character. Every character is a separator, so all the pieces are empty and are removed: the array has length 0 and parts[0] throws.

The fix

String[] parts = "1.18.2".split("\\.");

How to avoid it next time

Escape regex metacharacters with a double backslash, or use Pattern.quote for literal text.

Want the background? Read Regular expressions 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โ† #103#105 โ†’

Frequently asked questions

What is the bug in "The version string that splits into nothing"?

split takes a regular expression, and . matches any character. Every character is a separator, so all the pieces are empty and are removed: the array has length 0 and parts[0] throws. The faulty line is line 4: String[] parts = version.split(".");

How do I fix it?

Replace it with: String[] parts = "1.18.2".split("\\.");. Escape regex metacharacters with a double backslash, or use Pattern.quote for literal text.

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