public class Static { static { int x = 5; } static int x,y; public static void main(String args[]) { x--; myMethod(); System.out.println(x + y + ++x); } public static void myMethod() { y = x++ + ++x; } } |
Answer: | Compile time error |
INCORRECT The above code will not give any compilation error. Note that "Static" is a valid class name. Thus choice A is incorrect. In the above code, on execution, first the static variables (x and y) will be initialized to 0. Then static block will be called and finally main() method willbe called. The execution of static block will have no effect on the output as it declares a new variable (int x). The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1. In case the statement be "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1. Finally when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which result in 3 as the output. Thus choice D is correct. |
No comments:
Post a Comment
I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.