Search code examples
javaarraysobjectinstanceofscjp

instanceof operator in case of primitive and wrapper type array


int primitivI[] = {1,1,1};
Integer wrapperI[] = {2,22,2};


1. System.out.println(primitivI instanceof Object);//true
2. System.out.println(primitivI instanceof Object[]);//Compilation Error Why ????
3. System.out.println(wrapperI  instanceof Object);//true
4. System.out.println(wrapperI  instanceof Object[]);//true

Here I have two arrays of integer (primitve,Wrapper) type but I have got different result for instanceof operator

see the line number 2 and 4 line no 4 will compile successfully and give result true but in case of line 2, why does it result in a compilation error? From line 1 and 3 it is clear that the two arrays are instanceof object but in case of Object[], why do the results differ?


Solution

  • JLS 15.20.2. says :

    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 means that if at compile time the compiler knows that X cannot be instanceof Y, the expression X instanceof Y would give a compile time error.

    You can get simpler examples that don't compile, without trying with arrays :

    String s = "dgd";
    System.out.println(s instanceof Integer);
    

    Similarly, your 2nd example doesn't compile, since int[] cannot be cast to Object[]. All your other examples compile, since primitivI can be cast to Object and wrapperI can be cast to both Object and Object[].