🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Creational Patterns in Java: all 10 questions

Quiz: Creational Patterns in Java · Question 4 of 10

What does this print? (code)

What does this print?

class Counter {
    private static final Counter INSTANCE = new Counter();
    private int value = 0;
    private Counter() {}
    static Counter get() { return INSTANCE; }
    int next() { return ++value; }
}

public class Main {
    public static void main(String[] args) {
        Counter.get().next();
        Counter.get().next();
        System.out.println(Counter.get().next());
    }
}
  1. A.1
  2. B.0
  3. C.3
  4. D.Compilation error
Answer & explanation

Correct answer: 3

All three calls use the same single object, so value goes 1, 2, 3.

Can you get the rest right without peeking?

Take the timed Quiz: Creational Patterns in Java quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →