This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array element initialization" Watch "Array element initialization" New topic
Author

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
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
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
Bartender

Joined: Oct 14, 2005
Posts: 18115
    
    8

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: http://aspose.com/file-tools
 
subject: Array element initialization
 
Similar Threads
Please explain the output of this code snippet
STILL WAITING FOR A SATISFACTORY REPLY!!! :(
Variable scoping
Static Int and Methods
Is it possible to invoke a method before even the object gets created?