Instanceof - Incompatible Conditional Operand Types

The following compiled files:

Object o = new Object(); System.out.println(o instanceof Cloneable); 

But this is not so:

  String s = new String(); System.out.println(s instanceof Cloneable); 

Compiler error.

What is the problem?

+49
java instanceof
Mar 31 '10 at 8:10
source share
3 answers

A more egregious embodiment of your problem is this:

 if ("foo" instanceof Number) // "Incompatible conditional operand types String and Number" 

This is specified in JLS 15.20.2 instanceof type comparison operator :

 RelationalExpression: RelationalExpression instanceof ReferenceType 

If the conversion of the RelationalExpression to ReferenceType is rejected as a compile-time error, then the relational instanceof expression also generates a compile-time error. In such a situation, the result of the instanceof expression can never be true.

That is, since this expression expression generates a compile-time error:

 (Number) "foo" 

so this expression should be:

 ("foo" instanceof Number) 



Your case is a little more subtle, but the principle is the same:

  • String is the last class
  • String does not implement Cloneable
  • Therefore you cannot do (Cloneable) aString
  • Therefore you also cannot make aString instanceof Cloneable
+47
Mar 31 '10 at 9:41
source share

A related issue that I recently encountered (and which brought me to this page before I figured out what was going on) is that the Eclipse environment may incorrectly report "Incompatible conditional operand types" in the "instanceof" expression from due to the missing import statement for the type to the right of instanceof. I spent some time trying to figure out how the types in question can be incompatible before finding out that missing imports cause the whole problem. I hope this information saves someone a little.

+147
Jan 04 '12 at 19:10
source share

The compiler knows that String is the final class and does not implement Cloneable . Thus, no String instance can ever be a Cloneable instance. This prevents you from thinking that you have a meaningful test, when in fact it will always print β€œfalse”.

+28
Mar 31 '10 at 8:12
source share



All Articles