I know there are lot of questions on Singleton pattern. But here what I would like to know about the output which might also cover how \"static\" works in Java.
You cannot invoke the main method in the class until it has been properly initialized (i.e. static fields and static blocks have been evaluated). When it is initialized, an instance of your singleton is created by invoking the private constructor. Later the main method is invoked.
The class in question has a static field to which you assing a value. Since the field is static it must be initialized before the class can be used in any context, that is, it must receive a value. In this case its value happens to be an instance of the same class. This is what triggers your private costructor during class initialization.
If you want to delve into the process and understand it better please refer to the Java Laguage Specification. More specifically in the section12.4 Initialization of Classes and Interfaces you will find further details.
Class gets loaded and initialized first by classloader of JVM. And JVM while initializing, scans the class (Singleton) and while doing that it initializes static variable which is in the first line. That variable calls the constructor and prints line in it. Once class is initialized, it will invokes main method and hence prints the statement inside it.
You should rather declare it as final
private static final Singleton currentSingleton = new Singleton();
Answer to your both questions From JLS#8.3.2. Initialization of Fields
If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4.2).
Before the control gets to main() method, the class needs to be initialized. Since you initialize the currentSingleton
inline with declaration, this initialization takes place before main(), during class loading.
whenever control comes to any class for the first time, all the static initializations take place first. That's why your static object is being instantiated before anything else by calling it's constructor.
The new Singleton()
statement is the first to be executed because the currentSingleton
static field must be initialized; this means that memory for the Singleton object being created is allocated and its constructor is executed prior to assign the resulting object to the field variable.
This is the reason of the System.out.println("Singleton private constructor...");
line being executed before the assignment.
Moreover static field initialization occur as soon as the class is referenced and calling the main function of the Singleton class means refer it and this is the reason the initialization is executed before the main method.