LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 18

A singleton with a private constructor 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
final class AppConfig {
    private static AppConfig instance;
    static int constructed = 0;
    String theme = "light";

    private AppConfig() { constructed++; }

    static AppConfig get() {
        if (instance == null) instance = new AppConfig();
        return instance;
    }
}

public class Main {
    public static void main(String[] args) {
        AppConfig.get().theme = "dark";
        AppConfig c = AppConfig.get();
        System.out.println(c.theme + " " + AppConfig.constructed + " " + (c == AppConfig.get()));
    }
}
  • A dark 1 true Correct
  • B light 2 false
  • C dark 2 true
  • D light 1 true
Correct Answer: Option A

The private constructor can run only inside the class, and get() creates the object only once. (This lazy version is not thread-safe; see the static keyword topic for better ones.)

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