Is an array a primitive type or an object (or something else entirely)? Is an array a primitive type or an object (or something else entirely)? arrays arrays

Is an array a primitive type or an object (or something else entirely)?


There is a class for every array type, so there's a class for int[], there's a class for Foo[]. These classes are created by JVM. You can access them by int[].class, Foo[].class. The direct super class of these classes are Object.class

public static void main(String[] args){    test(int[].class);    test(String[].class);}static void test(Class clazz){    System.out.println(clazz.getName());    System.out.println(clazz.getSuperclass());    for(Class face : clazz.getInterfaces())        System.out.println(face);}

There's also a compile-time subtyping rule, if A is subtype of B, A[] is subtype of B[].


The Java Language Specification should give you an idea:

The direct superclass of an array type is Object.

Every array type implements the interfaces Cloneable and java.io.Serializable.

Moreover:

An object is a class instance or an array.

So arrays are not instances and therefore you don't need a constructor to create them. Instead you use the Array Creation Expressions.


See the below code. It compiles:

    int[] arr = new int[2];    System.out.println(arr.toString());

Now, on any primitive type, you cannot call a method(toString()) defined in Object class (Or, any method for that matter)... So, an array is essentially an Object.

OK, here you go:

From the JLS Section 4.3:

There are four kinds of reference types: class types (§8), interfacetypes (§9), type variables (§4.4), and array types (§10).

And, Section 10:

In the Java programming language, arrays are objects (§4.3.1), aredynamically created, and may be assigned to variables of type Object(§4.3.2). All methods of class Object may be invoked on an array.

So, from the first quote, Array is not actually a class... It is another type. But, essentially arrays are objects, though not of some Class, but they are of Array type. So they are not instances of some class, and may be objects of array are defined to be created that way...