It's not a secret anymore!
The moose likes Beginning Java and the fly likes instanceof Object [] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instanceof Object []" Watch "instanceof Object []" New topic

instanceof Object []

Juliet Meguma

Joined: Oct 07, 2004
Posts: 5

In my Java book, I just read that the following line is not legal:

if (x instanceof Object[] )

The reason given is that "the array (x) may be of a primitive type, in which case the test will fail". And that's the extent of the explanation - which left me confused.

So I wrote a little test for myself, where x is an int array. When i tried to compile code with that illegal line in it I got a compiler error "Inconvertible types".

Does the compiler test that
1) both arguments are arrays (test passes)
2) element types of both arrays are the same - but it uses arithmetic promotion to promote the int type up to an Object type before doing so (which results in the "Inconvertible types" error)?

Am I on the right track or waaaay off..?

Any help would be really appreciated
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
The idea is that if the compiler can prove that no object that could be referred to by the left operand could ever be referred to by the right operand, it's a compile time error.

See this thread:

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: instanceof Object []
It's not a secret anymore!