Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
you cant declare static variables inside a static block, that will result in a compiler error.Anything you want to initialize before the constructor is run should be done in static block.
In the example code you have given, x is initialized with 5 ( inside static block) but that x variable is going out of scope once the static block execution is complete.so the code in main method is accessing the x and y declared outside the static block which have default values 0.That explains why you are getting an output of 3.
but static block has to be executed first then why x cant assign it's value as 5?
The concept here to understand is of variable scope. Within the static block you are declaring and initializing a block scoped variable. Hence from the method main only the int primitive declared after the static block is visible as it's scope is wider than a block variable. Thus the variables within static block and outside static block are two different variables and not the same.
can't we declare and initialize(both) in the static block?
Yes you can declare and initialize only non-static variables in a static block but then that would make it a block scoped variable.
If you wanted to initialize the int primitive declared outside the static block from within the static block then you could have used forward referencing and said:
[ November 23, 2008: Message edited by: Harvinder Thakur ]