Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor calling in array creation

Tags:

java

arrays

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..

like image 674
saravanan Avatar asked Nov 30 '22 17:11

saravanan


2 Answers

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

like image 77
Bozho Avatar answered Dec 05 '22 03:12

Bozho


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
like image 30
Jcs Avatar answered Dec 05 '22 02:12

Jcs