🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Observer, Strategy and Decorator: all 10 questions

Quiz: Observer, Strategy and Decorator · Question 2 of 10

What does this print? (code)

What does this print?

import java.util.*;

public class Main {
    interface Listener { void on(String e); }

    public static void main(String[] args) {
        List<Listener> ls = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        ls.add(e -> sb.append("A").append(e));
        ls.add(e -> sb.append("B").append(e));
        for (Listener l : ls) l.on("1");
        ls.remove(0);
        for (Listener l : ls) l.on("2");
        System.out.println(sb);
    }
}
  1. A.A1B1A2B2
  2. B.A1B1B2
  3. C.B2
  4. D.A1B1A2
Answer & explanation

Correct answer: A1B1B2

Both listeners hear event 1; after the first is removed, only B hears event 2.

Can you get the rest right without peeking?

Take the timed Quiz: Observer, Strategy and Decorator quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →