This is the question from a mock exam. I have commented the values of x and y.
What will happen when you try to compile and run the code?
public class Static { static{ int x=5; } static int x,y; public static void main(String args[]) { x--;// Here x=-1 myMethod();//Now x=1 and y=0 System.out.println(x+y+ ++x);// 1 + 0 + 2
} public static void myMethod() { y=x++ + ++x;// Here y= -1 + 1 } }
Choose one A) Compile Time Error B) prints :1 C) prints :2 D) prints :3 E) prints :7 F) prints :8
Answer: D
3 is the output and I got the same. Hope this will help you,
The Static varible will be created and initilized before the static block. As Balazs point out in his post, The x created in the static block is a new x which only has scope in the static block. Instead of using int x = 5 in the static block, try using this.x = 5 or Static.x = 5. The static varible has to exist before you can work with it. Therefore, the static varible is created and initilized before the static block.
Hi Swapna Thanks for your reply.. itried it again .yeah!!! i got the output now.
I thnk previouly i've left some of the println stmts in the program as they are.tha's why i was getting the value 5. Now i tried it again..I got it . thank you
In the explanation with the code I gave before said that the static block variable will not have any effect on the output because it declares a new variable. I got it. But what if I want to access that static block variable in the main method, can I do it? If yes how do I do it?
I am so confused about this static blocks and variables .
Regards,
Swapna.
SCJP 1.4
And when my army is complete, I will rule the world! But, for now, I'm going to be happy with this tiny ad: