Question regarding the flow of execution with static blocks
posted 7 years ago
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?
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.