my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Question regarding the flow of execution with static blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question regarding the flow of execution with static blocks" Watch "Question regarding the flow of execution with static blocks" New topic
Author

Question regarding the flow of execution with static blocks

seena mathew
Greenhorn

Joined: Jun 14, 2009
Posts: 20
Given code (from Sanghera's book):


On running the program the output: 5, 11
I was thinking the output should be 4, 11.
I guess its because of x= x+1 is getting invoked before going to boardWalk.printIt().Why is x = x+1; getting invoked?
Thanks
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

The block that increments x is not a static block but an initializer block. These blocks are run before the constructor in top-to-bottom order. So when you call "new CodeWalkTwo()" that calls this initializer block, incrementing x from 3 to 4. You then pre-increment x again when printing, leading to 5.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
seena mathew
Greenhorn

Joined: Jun 14, 2009
Posts: 20
Thanks for your explanation.
 
Don't get me started about those stupid light bulbs.
 
subject: Question regarding the flow of execution with static blocks
 
Similar Threads
Recursive number problem
how to compare the values in arrays
Increment example
Two dimensional array total and sort
KB Question