ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class EventBus {
    private static EventBus instance;
    private EventBus() { System.out.print("created "); }
    public static EventBus getInstance() {
        if (instance == null) instance = new EventBus();
        return instance;
    }
}
// in main:
EventBus.getInstance();
EventBus.getInstance();
EventBus.getInstance();
  1. A. created
  2. B. created created created
  3. C. Compilation error: constructor is private
  4. D. It throws an exception on the second call

Correct answer: A. created

This is the classic (non-thread-safe but simple) lazy singleton pattern: instance is created only the first time getInstance() finds it null, printing "created" once; subsequent calls just return the already-created instance without constructing again.

More OOP with C++ and Java questions

Exams that ask this topic