static block

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Time
    New Member
    • Jan 2010
    • 77

    static block

    Execution in java begins from main(); but if we write static block; code in it gets executed first?...this shouldn't have happened; if execution begins in main..
  • pbrockway2
    Recognized Expert New Member
    • Nov 2007
    • 151

    #2
    Execution in java begins from main()
    Does it really? Your observation about code in a static block suggests otherwise.

    What happens at start up is described in the JVM specification in Chapters 2 and 5. From 2.17.1 Virtual Machine Startup we see "The Java virtual machine starts execution by invoking the method main of some specified class and passing it a single argument, which is an array of strings. This causes the specified class to be loaded (§2.17.2), linked (§2.17.3) to other types that it uses, and initialized (§2.17.4)."

    Those three steps (loading, linking and initialising) are described in the following sections. And they take place before any of the code in main() executes.

    Initialisation is the interesting bit here. According to 2.17.4 it involves executing static initialisers and initialisers for static fields (and doing the same for any super class.)

    So the bottom line seems to be that execution starts with the main() method being invoked, but that will involve executing other code in the class (and super classes) before the code in main() is executed.

    Comment

    Working...