instanceof operator in case of primitive and wrapper type array
Asked Answered
P

1

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?

Pahlavi answered 10/10, 2014 at 5:24 Comment(0)
O
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[].

Okeefe answered 10/10, 2014 at 5:57 Comment(3)
thanks..but if primitivI is instanceof Object then why its not an instance of Object[]..where the same case is true for wrapperIPahlavi
@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.Okeefe
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 truePahlavi

© 2022 - 2024 — McMap. All rights reserved.