Forums Register Login

A doubt on Arrays and Constructors

+Pie Number of slices to send: Send
Whenever we create an object(Any object),an Constructor for that class is called.
It is also mentioned in books that "any code that that uses the keyword new,will(if it runs successfully) cause the class constructor and all superclass constructors to run."
Now, my Question is:
An array is also an object and always created on heap,now when we create an array object(means array of reference or of primitives) then is any constructor called? if yes ,which?


Thanks and regards,
Kunal.
1
+Pie Number of slices to send: Send
The synthetic class that gets generated for the array may have a synthetic constructor that either does nothing but invoke super() or possibly also sets the array's length field. You could check the JLS or JVM spec, or play around with reflection to find out for sure.

It doesn't really matter though, as you can't refer to that constructor anyway.
+Pie Number of slices to send: Send
 

Kunal Vyas wrote:An array is also an object and always created on heap,now when we create an array object(means array of reference or of primitives) then is any constructor called? if yes ,which?


Not quite sure what your question is.

If you mean "what constructor is called when you create an array", refer to Jeff's answer. If you mean "what constructor is called for the objects in the array" the answer is none; a reference array is created containing nulls. You need to provide an object for each element in the array if you want to use them.

Winston
+Pie Number of slices to send: Send
And welcome to the Ranch
Please enjoy this holographic presentation of our apocalyptic dilemma right after this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 588 times.
Similar Threads
Java2 SCJP Array/New/Constructor contradition
default constructor
Abstract class constructor.
abtract class object is not created
How do arrays get created
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:34:38.