File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof operator" Watch "instanceof operator" New topic

instanceof operator

Unni Kainila
Ranch Hand

Joined: Jul 26, 2003
Posts: 45
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...?
Unni Kainila
Ranch Hand

Joined: Jul 26, 2003
Posts: 45
When I thought a bit more about my posting above...I casted b (Boolean) to an object and used the instanceof operator: 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

Joined: May 05, 2000
Posts: 13974
If the comparison can never be true then you will get a compile error.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
cyril vidal
Ranch Hand

Joined: Jul 02, 2003
Posts: 247

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..

SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Unni Kainila
Ranch Hand

Joined: Jul 26, 2003
Posts: 45
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

Joined: Dec 22, 2000
Posts: 14
Refer to JLS
I agree. Here's the link:
subject: instanceof operator
jQuery in Action, 3rd edition