TryBugHunt
javaInfinite loopHard

Infinite recursion in toString cyclic references

BugFind the bug and fix the code

What it should do

Format user name and group safely. Example: formatUserGroup("Alice") -> "Alice in Dev"

What happens instead

java.lang.StackOverflowError caused by mutual toString() recursion between User and Group

class Group {
    String name;
    Member member;
    Group(String n) { this.name = n; }
    @Override public String toString() {
        return name + " (" + member + ")";
    }
}

class Member {
    String name;
    Group group;
    Member(String n) { this.name = n; }
    // Cyclic toString() call!
    @Override public String toString() {
        return name + " in " + group;
    }
}

public class Main {
    public static String formatUserGroup(String name) {
        Group g = new Group("Dev");
        Member m = new Member(name);
        g.member = m;
        m.group = g;
        return m.toString();
    }

    public static void main(String[] args) {
        System.out.println(formatUserGroup("Alice"));
    }
}

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 infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

A hard Java debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

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)

What went wrong: Member.toString() calls Group.toString(), which in turn calls Member.toString(). This mutual recursion quickly exhausts the call stack and triggers a fatal StackOverflowError.

The fix: Break the circular print cycle by only printing the group's name (group.name) rather than printing the whole object recursively.

Remember: Never print bidirectional object references in toString() without breaking recursion cycles.

The pattern behind it: infinite loops.

More infinite loops to practise

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/0ff39965-55d1-4a4e-9d69-e4018f07b6c2" title="Debugging challenge: Infinite recursion in toString cyclic references" 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/0ff39965-55d1-4a4e-9d69-e4018f07b6c2">TryBugHunt</a></p>