• Post Reply Bookmark Topic Watch Topic
  • New Topic

A doubt on Arrays and Constructors  RSS feed

 
Kunal Vyas
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Marshal
Posts: 56595
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!