The following compiles fine:
Object o = new Object(); System.out.println(o instanceof Cloneable); But this doesn't:
String s = new String(); System.out.println(s instanceof Cloneable); A compiler error is thrown.
What is the problem?
A related issue that I have come across recently (and which led me to this page, before I figured out what was going on) is that the Eclipse environment can report "Incompatible conditional operand types" in an 'instanceof' expression erroneously due to a missing 'import' statement for the type on the right of the 'instanceof'. I spent a while trying to figure out how the types in question could possibly be incompatible before figuring out that a missing import was causing the whole problem. Hopefully this information saves somebody some time.
A more blatant incarnation of your problem is the following:
if ("foo" instanceof Number) // "Incompatible conditional operand types String and Number" This is specified in JLS 15.20.2 Type comparison operator instanceof:
RelationalExpression: RelationalExpression instanceof ReferenceTypeIf a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the
instanceofrelational expression likewise produces a compile-time error. In such a situation, the result of theinstanceofexpression could never be true.
That is, since this cast expression generates a compile time error:
(Number) "foo" so must this expression:
("foo" instanceof Number) Your case is a bit more subtle, but the principle is the same:
String is a final classString does not implement Cloneable (Cloneable) aString aString instanceof Cloneable If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With