Monday 18 February 2013

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

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

Choices:
a. Compiletime error
b. Runtime error
c. Prints : "I am true interface" followed by " I am true String"
d. Prints : "I am false interface" followed by " I am false String"
e. Prints : "I am true interface" followed by " I am false String"
f. Prints : "I am false interface" followed by " I am true String"
Answer :-
E is the correct choice.
The "instanceof" operator tests the class of an object at runtime.
It returns true if the class of the left-hand argument is the same as, or is some subclass of, the class specified by the right-hand operand.
The right-hand operand may equally well be an interface.
In such a case, the test determines if the object at left-hand argument implements the specified interface.
In the above case there will not be any compiletime or runtime error. The result of "t instance of MyInterface" will be true as "t" is the object of MyInstanceTest class which implements the MyInstance interface.

But the result of "s instanceof String" will be false as "s" refers to null.
Thus the output of the above program will be : "I am true interface" followed by " I am false String". Thus choice E is correct and others are incorrect.


No comments:

Post a Comment