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.
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.