Monday 11 February 2013

1. What will happen when you attempt to compile and run the following code?



1. What will happen when you attempt to compile and run the following code?



Choices:
a. Compiletime error
b. prints : 1
c. prints : 2
d. prints : 3
e. prints : 7
f. prints : 8

Answers:

D is the correct choice.
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 will be 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