Hasnain Abid Khanzada
Hasnain Abid Khanzada

Reputation: 165

Creating Array Object Java

I have seen many tutorial which describes that array is object and its object is referenced by the reference variable like this

int a[]=new int[5];

But the thing which is confusing me is that , as to create an object we need constructor like when creating a simple object like this

box b1=new box();

but when creating arrays object we are not calling any constructor instead we are writing like this int[5] so what is this ? and also what is the datatype of array object ?

Upvotes: 0

Views: 146

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

The array creation syntax for objects isn't really different than for primitives, e.g.

Box[] boxArray = new Box[5];

Now if you want to create boxes inside the array you would use the constructor syntax as:

boxArray[0] = new Box();

Note that I went ahead and capitalized box to Box, since starting class names with a capital letter is basically the accepted standard.

Upvotes: 2

Amber Beriwal
Amber Beriwal

Reputation: 1598

From the JLS 4.3.1 - Objects:

An object is a class instance or an array.

For class instantiation, we need constructors. Arrays does not represent a class, thus constructors are not required. Both classes and arrays have different creation styles. Refer JLS 15.9 and JLS 15.10.1

Regarding type of arrays, from JLS 10.1:

An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting.

Only few classes/interfaces are capable of holding arrays, Refer JLS 4.10.3.

Edit: So, int[] or any other array are called reference type, but not class. Objects are referenced by the reference types, not classes. From JLS 4.3,

There are four kinds of reference types: class types (§8.1), interface types (§9.1), type variables (§4.4), and array types (§10.1).

Upvotes: 1

Related Questions