← 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());
}
}
- A.1
- B.0
- C.3
- 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 →