File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Android Security Essentials Live Lessons this week in the Android 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: 38045
    
  22
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: 18541
    
    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.
 
Consider Paul's rocket mass heater.
 
subject: Array element initialization
 
Similar Threads
Variable scoping
STILL WAITING FOR A SATISFACTORY REPLY!!! :(
Is it possible to invoke a method before even the object gets created?
Please explain the output of this code snippet
Static Int and Methods