LearnFrenzy
Sign in Take a free test

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

Static fields initialised in order Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following Java program?

Main.java
class Settings {
    static final Settings INSTANCE = new Settings();
    static int loaded = 10;
    int snapshot;

    Settings() { snapshot = loaded; loaded++; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Settings.INSTANCE.snapshot + " " + Settings.loaded);
    }
}
  • A 0 10 Correct
  • B 10 11
  • C 0 1
  • D 10 10
Correct Answer: Option A

Static initialisers run top to bottom. INSTANCE is built while loaded is still 0 (snapshot = 0, loaded becomes 1); then loaded = 10 overwrites it.

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