Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array element initialization

 
Oceana Wickramasinghe
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys my question is this. When you create an object it calls the constructor, which initializes all the variables in the class that your object represents. But how do array elements get initialized? for example



No constructor calling happens here. But the output is 10. So how did x variable get initialized? Do arrays have their own classes and constructors? Can someone explain to me the technical aspect of this? Thank you
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You variable x isn’ an object, but a primitive. It is initialised to 10 by the assignment, but that does not apply to objects.
Yes, arrays do have their classes; you can find the class name like this:At no point do you call the constructor WrapTest(), so nothing happens there.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array elements get initialized just like instance variables do, they get initialized to the default value for their type. So int variables get initialized to 0, double variables get initialized to 0.0, and so on, and reference variables get initialized to null. This happens when the array is created.

I'm not sure I understand the question about your example code; is it not obvious that a[0] contains 10 at line 9 because you set it to 10 at line 8? That has nothing to do with initialization.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic