saravanan
saravanan

Reputation: 5417

constructor calling in array creation

int[] a=new int[4];

i think when the array is created ..there will be the constructor calling (assigning elements to default values) if i am correct..where is that constructor..

Upvotes: 5

Views: 3733

Answers (3)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

From a conceptual level, you could see the array creation as a array constructor, but there is no way for a programmer to customize the constructor, as array types have no source code, and thus can't have any constructors (or methods, by the way).

See my answer here for a conceptual view of arrays.

Actually, creating arrays is a primitive operation of the Java VM.

Upvotes: 0

Jcs
Jcs

Reputation: 13759

No, there is no such constructor. There is a dedicated opcode newarray in the java bytecode which is called in order to create arrays.

For instance this is the disassembled code for this instruction int[] a = new int[4];

0:  iconst_4      // loads the int const 4 onto the stack
1:  newarray int  // instantiate a new array of int 
3:  astore_1      // store the reference to the array into local variable 1

Upvotes: 7

Bozho
Bozho

Reputation: 597402

No, there is no such thing. Primitive array elements are initialized to the default primitive value (0 for int). Object array elements are initialized to null.

You can use java.util.Arrays.fill(array, defaultElementValue) to fill an array after you create it.

To quote the JLS

An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

If you use an initializer, then the values are assigned. int[] ar = new int[] {1,2,3}

If you are using an array creation expression (as in your example), then (JLS):

Each class variable, instance variable, or array component is initialized with a default value when it is created

Upvotes: 14

Related Questions