• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof operator

 
Unni Kainila
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am bit confused about the way the compiler treats the instanceof operator.
Here is a sample code:

I understand instanceof will tell you whether the reference on the LHS is an instance of type on RHS (including superclasses and interfaces).
What I DON'T understand is, WHY it is a compile time error (look at lines 6, 7 and 9 from the code above)? I would expect the instanceof operator returning "false" on those tests. Afterall, if I know what type to check the instanceof against, why should I run the test at all???
I searched for an answer in previous postings...but did not find one.
Can somebody please explain it...?
Thanks
 
Unni Kainila
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I thought a bit more about my posting above...I casted b (Boolean) to an object and used the instanceof operator:

...it worked without compiler error.
Again, are we expected to test instanceof against an "Object" reference or to a "compatible" type ONLY ?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the comparison can never be true then you will get a compile error.
 
cyril vidal
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression is assignment compatible (�5.2) with some other reference type.

Assignement conversion:

...
If the type of the expression (B]can not be converted to the type of the variable by a conversion permitted in an assignment context[/B]then a compile-time error occurs

In your example, object of type Boolean can never be converted to an object of type Integer, and vice-versa -> compile error.
When you assign b to Object o, then Boolean becomes assignement compatible with b, because each class extends Object.So, no more compile error..
 
Unni Kainila
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had wrong expectations...I thought I can check whether "anything" is an instanceof "something".....
Now it is clear, thanks for the details.
 
Mahendra Deshpande
Greenhorn
Posts: 14
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic