TryBugHunt
javaNull / UndefinedMedium

Weekday visit counter crashes on the first visit

BugFind the bug and fix the code

What it should do

visits lists the weekday of each visit (0 = Monday to 6 = Sunday). busiestDay(visits) returns the weekday with the most visits, the earliest one on a tie, so busiestDay([1, 3, 3, 5]) returns 3.

What happens instead

busiestDay([1, 3, 3, 5]) throws java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()".

public class Main {
    static int busiestDay(int[] visits) {
        Integer[] counts = new Integer[7];
        for (int d : visits) {
            counts[d]++;
        }
        int best = 0;
        for (int i = 1; i < 7; i++) {
            if (counts[i] > counts[best]) {
                best = i;
            }
        }
        return 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)

new int[7] is filled with zeros, but new Integer[7] is an array of object references, and every slot starts as null. counts[d]++ has to unbox the current value, add one and box it again, and unboxing null throws NullPointerException on the very first visit. The two array types look almost the same and both compile, yet their default values differ. Use primitive arrays (int[], double[]) for counters and totals. If you really need boxed values, fill the array first, for example with Arrays.fill(counts, 0).

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/e03865cb-ab49-4a41-84df-96020a3114f9" title="Debugging challenge: Weekday visit counter crashes on the first visit" 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/e03865cb-ab49-4a41-84df-96020a3114f9">TryBugHunt</a></p>