File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 19538
    
  16

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question regarding the flow of execution with static blocks
 
Similar Threads
Recursive number problem
Two dimensional array total and sort
KB Question
Increment example
how to compare the values in arrays