Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
The moose likes Java in General and the fly likes Array element initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Badass: Making Users Awesome this week in the Game Development forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array element initialization" Watch "Array element initialization" New topic

Array element initialization

Oceana Wickramasinghe
Ranch Hand

Joined: Mar 02, 2011
Posts: 77
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

Joined: Oct 13, 2005
Posts: 41531
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

Joined: Oct 14, 2005
Posts: 19357

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.
I agree. Here's the link:
subject: Array element initialization