LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 18

An enum singleton with state Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

Main.java
enum IdGenerator {
    INSTANCE;
    private long next = 1000;
    synchronized long nextId() { return ++next; }
}

public class Main {
    public static void main(String[] args) {
        IdGenerator a = IdGenerator.INSTANCE, b = IdGenerator.valueOf("INSTANCE");
        System.out.println(a.nextId() + " " + b.nextId() + " " + (a == b) + " " + IdGenerator.values().length);
    }
}
  • A 1001 1002 true 1 Correct
  • B 1001 1001 false 1
  • C 1000 1001 true 1
  • D 1001 1002 false 2
Correct Answer: Option A

There is only one INSTANCE, so both references share the same counter.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links