TryBugHunt
javaNull / UndefinedMedium

Mail server lookup crashes on a mistyped address

BugFind the bug and fix the code

What it should do

mailServer(email) returns the lower-case domain of an email address, or "unknown" if the address has no @, so mailServer("ann@Example.COM") returns "example.com" and mailServer("not-an-email") returns "unknown".

What happens instead

mailServer("not-an-email") throws java.lang.NullPointerException: Cannot invoke "String.toLowerCase()".

public class Main {
    static String domainOf(String email) {
        int at = email.indexOf('@');
        if (at < 0) {
            return null;
        }
        return email.substring(at + 1);
    }

    static String mailServer(String email) {
        String domain = domainOf(email);
        return domain.toLowerCase();
    }
}

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)

domainOf signals "no domain" by returning null, which is a perfectly reasonable design, but then every caller must check for null before using the result. mailServer calls toLowerCase() on it straight away, so a bad address crashes the program instead of producing "unknown". The fix is in the caller: handle the null case before using the value. When you write a method that can return null, the risk moves to every place it is called. Java's Optional<String> makes that possibility visible in the type, so callers cannot forget it as easily.

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/dc4bbf24-5adb-4469-9b90-3564a48a8594" title="Debugging challenge: Mail server lookup crashes on a mistyped address" 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/dc4bbf24-5adb-4469-9b90-3564a48a8594">TryBugHunt</a></p>