I am writing a mock exam, in that i came over with this question on instanceof operator, The question is as follows:
Which of the following statements are true? 1.The instanceof operator can be used to determine if a reference is an instance of a class, but not an interface. 2.The instanceof operator can be used to determine if a reference is an instance of a particular primitive wrapper class. 3.The instanceof operator will only determine if a reference is an instance of a class immediately above in the hierarchy but no further up in the inheritance chain. 4. The instanceof operator can be used to determine if one reference is of the same class as another reference thus.
The answer given is 2. Can any one explain me why? Thanks in advance.
The instanceof operator tests whether its first operand is an instance of its second. op1 instanceof op2
op1 must be the name of an object and op2 must be the name of a class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.
Hope the following lines from JLS be of some help to u.
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (�15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
Reasonable people adapt themselves to the world. Unreasonable people attempt to adapt the world to themselves. All progress, therefore, depends on unreasonable people.
Originally posted by vishnu priya parimi: The answer given is 2. Can any one explain me why?
Which one do you think could be true, too, and why? Is there any reason you doubt that 2 could apply?
BTW, I think the answers are worded a little bit sloppily: a reference is not an instance of a class, it references ("points to") an instance of a class - and that instance is checked by the operator.
That's important because the reference has a type, too (the one you declare in the source code), but that is not checked by instanceof.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus