Note that there are some explanatory texts on larger screens.

plurals
  1. POUse and flow of Static statements in Singleton Program
    primarykey
    data
    text
    <p>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.</p> <pre><code>public class Singleton { private static Singleton currentSingleton = new Singleton(); public static Singleton getSingleton() { return currentSingleton; } private Singleton() { System.out.println("Singleton private constructor..."); } public static void main(String[] args) { System.out.println("Main method..."); } </code></pre> <p>    }</p> <p>This is the output from running the code...</p> <blockquote> <p>Singleton private constructor... <br> Main method...</p> </blockquote> <p>When I debugged this code, control went first to line <code>System.out.println("Singleton private constructor...")</code> and prints. (private static variable currentSingleton is still null at this point) <br> Then it goes to line <br> <code>private static Singleton currentSingleton = new Singleton();</code> and then initializes the private variable. Then at last, it goes to main() method and prints.</p> <p>My Questions are:</p> <ol> <li>Why it first prints "Singleton private constructor..." which is in private constructor. I thought control should first go to main() method since it is the entry point. Also I am not creating any instance anywhere (except in variable initialization).</li> <li>Later it goes to static variable instantiation line (currentSingleton=null at this point) <br> <code>private static Singleton currentSingleton = new Singleton();</code> Though currentSingleton gets a value here, why constructor is not called again?</li> </ol> <p>Mainly I want to know the flow of control of this program.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload