my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Initializer Doubt - Bert please explain.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Initializer Doubt - Bert please explain.." Watch "Array Initializer Doubt - Bert please explain.." New topic

Array Initializer Doubt - Bert please explain..

Jayant Raj
Ranch Hand

Joined: Mar 11, 2004
Posts: 42
Hi All,

Please help me out in understanding the following code :

Why is there a type mismatch while converting from Pizza[] to Object ? Also let me know whether Object[] is-a Object?

regards,<br />Jayant Raj<br /> <br />SCJP 1.4 [98%]<br />SCWCD 1.4 [91%]<br />SCBCD [In Progress]
Sebastien Col

Joined: Aug 18, 2005
Posts: 13

The problem is that when you initialize a variable, the type of the init value must match the type of the variable.
Here, you have an Object type variable named "objects2" and you have a Pizza[] init value. Types don't match.

Arrays are extensions of the Object class. It is then possible to affect an array to an Object variable. The following code is valid:

Object[] objectsTab = {new Pizza(), new Pizza()};
Object obj = objectsTab;

I guess the difference is that during initialization, the JVM will allocated memory space to store the init value. I think that's why types must match, so that the JVM will have necessary information to allocate enough memory.

Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245

It the above code the compiler cannot determine the type of array to be cerated. It can be Pizza[] or Object[]. So statement like this is illegal.

The following code compiles without error.

[ August 25, 2005: Message edited by: Vlado Zajac ]
I agree. Here's the link:
subject: Array Initializer Doubt - Bert please explain..
It's not a secret anymore!