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

Nirav Prajapati
  • 2,987
  • 27
  • 32

1 Answers1

1

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

Eran
  • 387,369
  • 54
  • 702
  • 768
  • thanks..but if primitivI is instanceof Object then why its not an instance of Object[]..where the same case is true for wrapperI – Nirav Prajapati Oct 10 '14 at 06:25
  • 1
    @Nirav primitivel is an array, and therefore can be cast to an Object, since an array is an Object. It cannot be cast to Object[], because it's an array of primitive type, so it can't be cast to an array of Object. – Eran Oct 10 '14 at 06:29
  • got it ...if i take int a = 10 and then check with instanceof then it will also give me compilation error. here i am checking with array to instanceof Object so thats why it gives me result true – Nirav Prajapati Oct 10 '14 at 06:36