1: public class StringInstanceOfTest {
2: public static void main(String[] args) {
3: String s = null;
4: if(s instanceof String){
5: System.out.println("s is instance of String");
6: }
7: else{
8: System.out.println("s is not an instance of String");
9: }
10: }
11: }
Output :
A. Compilation fails.
B. Throws Exception at line 4.
C. Prints “s is instance of String”.
D. Prints “s is not an instance of String”.
Answer : D
There is no problem with the syntax of the code so there is option A is incorrect. The code compiles perfectly. Instanceof operator does not throw any exception so B is incorrect. The answer is either C or D.
The instanceof
operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
When using the instanceof
operator, keep in mind that null
is not an instance of anything.
So from the above explanation option D is correct .
No comments:
Post a Comment