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.


public class GetComponentType {
  public static void main(String str[]){
    int[] intArray = {1,2,3,4};
    double[] doubleArray = {1.0,2.2,3.5,4.8};
    Class intArrayClass = intArray.getClass();
    Class doubleArrayClass = doubleArray.getClass();
    System.out.println("\"intArrayClass\" component type => "
      + intArrayClass.getComponentType());
    System.out.println("\"doubleArrayClass\" component type => "
      + doubleArrayClass.getComponentType());

The output of this program is reported below; as we can see, when a Class object represents a primitive type (such as int or double) its toString() method (which is called implicitly when the object is passed to the println() method) returns simply the name of the primitive type.

"intArrayClass" component type => int

"doubleArrayClass" component type => double