sbhatla sbhatla - 1 year ago 73
Java Question

When declaring Integer array in Java, why does it not need round brackets

When I declare an Integer array in Java, I get no error when I do this

Integer[] ans = new Integer[10];

but I get an error if I do this-

Integer[] ans = new Integer[10]();

Why is this? "Integer" is an Object, and for any object, don't we need round brackets () to initialize it?

EDIT: Question is not duplicate of How to declare an array

My question asks why round brackets are not needed during declaration, not how to declare it.

Answer Source

If you instantiate a new Array you do not instantiate the class of its members. The () is selecting a constructor, Arrays do not have this possibility.

If you check the Java Language Specification 10.3 you read:

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

An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. ...

An array initializer creates an array and provides initial values for all its components.

As you can see there is no constructor mentioned.