Constructor call when creating an array

int[] a=new int[4]; 

I think when the array is created .. there will be a constructor call (assigning elements to default values) if I'm right ... this is that constructor ..

+4
source share
3 answers

No, this does not happen. Primitive elements of an array are initialized by default for a primitive value ( 0 for int ). Elements of an array of objects are initialized to null .

You can use java.util.Arrays.fill(array, defaultElementValue) to populate the array after creating it.

To quote JLS

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

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

If you use 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.

+14
source

No, there is no such constructor. In java bytecode, the operation code newarray , which is called to create arrays.

For example, this is the disassembled code for this command 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 
+7
source

At the conceptual level, you can see the creation of an array as an array constructor, but the programmer does not need to configure the constructor, since the types of arrays do not have source code and, therefore, cannot have any constructors (or methods, by the way).

See my answer here for a conceptual representation of arrays.

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

0
source

Source: https://habr.com/ru/post/1338709/


All Articles