TryBugHunt
javaOtherEasy

Adding drinks to the cafe menu crashes

BugFind the bug and fix the code

What it should do

buildMenu(extras) returns the standard drinks "tea" and "coffee" followed by any extra drinks, so buildMenu(["juice"]) returns ["tea", "coffee", "juice"].

What happens instead

buildMenu(["juice"]) throws java.lang.UnsupportedOperationException, and so does buildMenu([]).

import java.util.*;

public class Main {
    static List<String> buildMenu(List<String> extras) {
        List<String> menu = List.of("tea", "coffee");
        menu.addAll(extras);
        return menu;
    }
}

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 mutation and copying bugs pattern

Two references to one object, so changing one changes both; shallow copies of lists.

What you'll practise

An easy Java debugging exercise about mutation and copying bugs: two references to one object, so changing one changes both; shallow copies of lists.

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)

List.of creates an immutable list. It has the same List type as an ArrayList, so the compiler is happy with addAll, but at runtime every method that would change it throws UnsupportedOperationException, even adding zero items. Arrays.asList and Collections.unmodifiableList have similar limits. When you need a starting list that you will add to, copy it into a mutable one: new ArrayList<>(List.of(...)). If an UnsupportedOperationException appears on a call to add, remove or set, check where the list was created rather than where it was changed.

The pattern behind it: mutation and copying bugs.

More mutation and copying bugs 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/ae96e20e-3f03-4eda-8423-cb36aa91682f" title="Debugging challenge: Adding drinks to the cafe menu crashes" 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/ae96e20e-3f03-4eda-8423-cb36aa91682f">TryBugHunt</a></p>