TryBugHunt
javaNull / UndefinedHard

Config value is missing although it is in the file

BugFind the bug and fix the code

What it should do

config is a list of name=value pairs separated by semicolons, with optional spaces around names and values. getSetting(config, key) returns the value for key, so getSetting("host=db.local; port=5432", "port") returns "5432".

What happens instead

getSetting("host=db.local; port=5432", "port") returns null. getSetting("host=db.local;port=5432", "port") returns "5432".

import java.util.*;

public class Main {
    static String getSetting(String config, String key) {
        Map<String, String> settings = new HashMap<>();
        for (String line : config.split(";")) {
            int eq = line.indexOf('=');
            if (eq > 0) {
                String name = line.substring(0, eq);
                String value = line.substring(eq + 1).trim();
                settings.put(name, value);
            }
        }
        return settings.get(key);
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the null and undefined errors pattern

A NullPointerException from a reference that was never assigned.

What you'll practise

A hard Java debugging exercise about null and undefined errors: a NullPointerException from a reference that was never assigned.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

Map lookups need an exact key match. Splitting "host=db.local; port=5432" on ; leaves " port=5432" with a leading space, so the name stored in the map is " port". The value is trimmed, but the name is not, and get("port") finds nothing and returns null. Nothing crashes here, the setting just looks absent. When a key you can see in the input is missing from a map, print the keys with visible delimiters, for example "[" + name + "]", to spot stray whitespace or case differences. Normalise keys the same way when storing and when looking up.

The pattern behind it: null and undefined errors.

More null and undefined errors to practise

Related errors

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/9e008e22-dcb9-45d5-966b-5c9404f56049" title="Debugging challenge: Config value is missing although it is in the file" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/9e008e22-dcb9-45d5-966b-5c9404f56049">TryBugHunt</a></p>