Search code examples
javainstanceofcloneable

instanceof - incompatible conditional operand types


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?


Solution

  • 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 ReferenceType
    

    If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression 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 class
    • String does not implement Cloneable
    • Therefore you can't do (Cloneable) aString
    • Therefore also you can't do aString instanceof Cloneable