This week's book giveaway is in the Java 9 forum.
We're giving away four copies of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications and have Sander Mak & Paul Bakker on-line!
See this thread for details.
Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Order of Initialization, Page 202 (Java OCA 8 Programmer I Study Guide, Sybex)  RSS feed

 
John Consorti
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Could someone please explain the below blocks of code to me and why the output is "1 2 5 Now in main".  I am having a hard time grasping this as following the rules found on page 202 I assumed there would be a different output.

 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Consorti wrote:Could someone please explain the below blocks of code to me and why the output is "1 2 5 Now in main".

It is fairly simply (if you know what's going on ). When a class is loaded (by the JVM), static initializer blocks will run in the order they appear in the class declaration from top to bottom. To execute the main method, the class InitTest2 needs to be loaded, so "1 2 5 " is printed and then the main method executes, printing "Now in main". No instances of the InitTest2 class are created in the executed code, so the instance initializer blocks and constructor will not execute.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!