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.
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
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.
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 contains 10 at line 9 because you set it to 10 at line 8? That has nothing to do with initialization.