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

3 Answers 3

14

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

Sign up to request clarification or add additional context in comments.

5 Comments

then where they get default values ..directly by the jvm?
@saravanan didn't [ this ](stackoverflow.com/questions/4873673/…) answer
@Bozho: thanks for your answer ..i have another doubt ..why we can't assign index value in anonymous array creation int[] ar = new int[] {1,2,3}....
what do you mean "index value" ?
because it is implied by the number of elements you specify in the initializer?
7

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.