JVM Knowledge

Every array has an associated Class object, shared with all other arrays with the same component type.

Although an array type is not a class, the Class object of every array acts as if:

  • The direct superclass of every array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.

Example 10.8-1. Class Object Of Array

class Test1 {
    public static void main(String[] args) {
        int[] ia = new int[3];
        System.out.println(ia.getClass());
        System.out.println(ia.getClass().getSuperclass());
        for (Class<?> c : ia.getClass().getInterfaces())
            System.out.println("Superinterface: " + c);
    }
}

This program produces the output:

class [I
class java.lang.Object
Superinterface: interface java.lang.Cloneable
Superinterface: interface java.io.Serializable

where the string "[I" is the run-time type signature for the Class object "array with component type int".

Example 10.8-2. Array Class Objects Are Shared

class Test2 {
    public static void main(String[] args) {
        int[] ia = new int[3];
        int[] ib = new int[6];
        System.out.println(ia == ib);
        System.out.println(ia.getClass() == ib.getClass());
    }
}

This program produces the output:

false
true

While ia and ib refer to different arrays, the result of the comparison of the Class objects demonstrates that all arrays whose components are of type int are instances of the same array type (namely int[]).