TryBugHunt
javaNull / UndefinedEasy

Shelf label reads cup: null

BugFind the bug and fix the code

What it should do

stockLabel(stock, item) builds a shelf label like "pen: 3". Items that are not in the map are out of stock, so stockLabel({"pen": 3}, "cup") returns "cup: 0".

What happens instead

stockLabel({"pen": 3}, "cup") returns "cup: null".

import java.util.*;

public class Main {
    static String stockLabel(Map<String, Integer> stock, String item) {
        return item + ": " + stock.get(item);
    }
}

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

An easy 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.get returns null for a missing key. Unlike arithmetic, string concatenation does not crash on null; it quietly turns it into the four letters "null". That makes this kind of bug easy to ship, because nothing fails and the text only looks wrong when someone reads it. The fix is to decide what a missing key means (here, zero in stock) and say so with getOrDefault. If you ever see the word null in user-facing text, trace the value back to where it was looked up and add the missing default there.

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/499081e3-1d4e-48b8-8374-70679db77843" title="Debugging challenge: Shelf label reads cup: null" 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/499081e3-1d4e-48b8-8374-70679db77843">TryBugHunt</a></p>