• How to identify array objects

    In computer programs, arrays are useful to group and access multiple elements of the same type. In Java, arrays (both single- and multi-dimensional) can be created from either primitive types (such asint,float, etc.) or classes. Every array belongs to a class that contains information on the type of array elements and the number of dimensions; as with any other class, the Class object corresponding to an array can be retrieved with thegetClass() method of thejava.lang.Object class.

    Given a Class object, we can check whether it corresponds to an array object with the isArray() method, which returns true for array objects and false otherwise. The following example demonstrates the use of this method. After creating an array of integer values and a String object, we retrieve the corresponding Class objects and then we call isArray() on these objects.

  • How to retrieve the component type of an array

    In Java, every array is an object, regardless of whether array elements are objects or primitive types. As a consequence, every array has a corresponding java.lang.Class object, which can be retrieved by calling the getClass() method of java.lang.Object. From the Class object associated to an array, we can retrieve the type of array elements via the getComponentType()method, which returns the Class object representing the element type. Class objects can represent not only classes and interfaces, but also primitive types, so the getComponentType() method works for any array object; if the object on which this method is called does not represent an array, then the method returns null.

    In the following example, we first declare two arrays, and then retrieve their component types and print them on the standard output.