TryBugHunt
javaNull / UndefinedMedium

Auction crashes before looking at a single bid

BugFind the bug and fix the code

What it should do

highestBid(bids) returns the largest bid, or 0 when there are no bids, so highestBid([300, 450, 120]) returns 450 and highestBid([]) returns 0.

What happens instead

highestBid([300, 450, 120]) throws java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()". highestBid([]) returns 0.

import java.util.*;

public class Main {
    static int highestBid(List<Integer> bids) {
        Integer best = null;
        for (Integer b : bids) {
            if (b > best || best == null) {
                best = b;
            }
        }
        return best == null ? 0 : best;
    }
}

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 medium 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)

best starts as null to mean "no bid seen yet", and the condition does check for that, but in the wrong place. || evaluates left to right, so b > best runs first, and comparing with > unboxes best, which is null on the first pass. The null check on the right would have saved it, but it is never reached. Short-circuit operators only protect you when the guard comes first: best == null || b > best never evaluates b > best while best is null. The empty list test passes because the loop body never runs, which is why it cannot be the only test.

The pattern behind it: null and undefined errors.

More null and undefined errors to practise

Seen this error in your own code?

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/d2d0e432-8dce-4654-95e6-77c8a68e4c72" title="Debugging challenge: Auction crashes before looking at a single bid" 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/d2d0e432-8dce-4654-95e6-77c8a68e4c72">TryBugHunt</a></p>