Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding the flow of execution with static blocks

 
seena mathew
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
seena mathew
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic