Java OCA OCP Practice Question 367

Question

Which of the following statements are true?

Select 1 option

For any non-null reference o1,
A. the expression  (o1 instanceof o1)     will always yield true. 
B. the expression  (o1 instanceof Object) will always yield true. 
C. the expression  (o1 instanceof o1)     will always yield false. 
D. the expression  (o1 instanceof Object) may yield         false. 
E. None of the above. 


Correct Option is  : B

Note

A. is wrong, instanceof operator does not accept objects as the right hand side operand.

The operand at the right hand side should be a class.

Therefore, this expression will not compile.

B. is wrong, because all objects in Java derive from Object class.

C. is wrong, it is wrong for the same reason as option 1.

D. is wrong, since all objects in Java derive from Object class, there is no way it will ever return false.

instanceof operator returns true even if the Right Hand Side is a super class.

For example,

class Animal  {} 
class Dog extends Animal  {  } 
Dog d = new Dog (); 

d instanceof Animal will be true because even though d is actually an instance of Dog, since Dog is a subclass of Animal, Dog IS-A Animal.




PreviousNext

Related