• Post Reply Bookmark Topic Watch Topic
  • New Topic

instanceof operator analysis  RSS feed

 
Roopam Samal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What is the result?
A. w-f
B. f-p w-f
C. w-f b-f
D. f-p w-f b-f
E. Compilation fails.
F. An exception is thrown at runtime.
Answer: B


Hello everyone I have understood the code.I'm writting below my understanding please rectify it if necessary

Here 1st lets check is there any possibility of compilation error.

As f is reference of Fish type so it can hold instance of Walleye or Perch
(i.e.,Fish type reference can be assigned to Walleye or Perch object as they lie below it in class hierarchy) and here test is done with respect to Perch so compiler doesn't complain
then in second if expression w is reference of Walleye type so it can hold instance of Walley which is a Fish and here its tested with respect to Fish so compiler doesn't complain
In 3rd case b is reference of BlueGill type it can hold BlueGill instance or its subtype and if its a Fish(i.e.,subtype of Fish) then instaneof check might be true so compiler doesn't complain.

As there is no possibility if compilation error lets move runtime where we will check which if expression gives true and what gives false

Here f holds Walleye object which is a Perch so if it is checked with instanceof Perch then it gives true so f-p is printed
next w holds Walleye object which is a Fish so if its checked with instanceof Fish then it gives true so w-f is printed
then b holds BlueGill object which isn't Fish so if its checked with instanceof Fish then it gives false so b-f isn't printed.


kindly check my understanding and rectify it accordingly


thanks in advance
with regards
Roopam
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roopam Samal wrote:kindly check my understanding and rectify it accordingly

Seems about right. The main thing to remember about instanceof is that it works downwards (in 'hierarchy' terms), so:

x instanceof <Class>

will return true if, and only if, the following conditions are BOTH true:
  • x is NOT null.
  • x's class == <Class>, OR x's class is a subtype (note: NOT a supertype) of <Class>.

  • HIH

    Winston
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Please always tell us where such questions come from, to avoid copyright problems, etc.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!