I am currently studying for the OCAJP I Certification and as I am working myself through
a lot of exam questions I stumbled upon this one:
It asks what the output is. Possible answers are:
- Compilation fails
I tried it out, and the answer is 5. I don't exactly get why, though...
What I can see here is that the statics are initialized when the Class is loaded.
First, x is asigned the value of 2, and z is declared as static.
Then, below the main() Method, in a static-Block, a new Variable x is defined, with the value 3.
Seems, it kind of "hides" the original Class-Variable x defined before the
main() Method. After that, z gets assigned the Value of x. But NOT the Value of the "new" x
(the one below the main() Method)! Instead, it uses the Value of the "hidden" x (the one
before the main() Method).
The System.out.println(x+z) then prints 5.
So in the static Block a complete new Variable x get's defined, which is only valid in that Block,
am I right? Then z gets assigned the Value of that new x, which is 3. In the main() Method
the Class.x (the one before the main() Method) gets used.
I hope I got it all right;)