Get the Component Type of an Array Object in Java


In order to get the component type of an Array Object in Java, we use the getComponentType() method. The getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null.

Declaration − The java.lang.Class.getComponentType() method is declared as follows -

public Class<?> getComponentType()

Let us see a program to the get the component type of an Array Object in Java -

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int[] array = new int[] {1,2,3};
      // obtain the Class of the component type
      Class arrayClass = array.getClass();
      // obtaining the component type
      Class component = arrayClass.getComponentType();
      if (component != null) {
         System.out.println("Component type is " + component.getName());
      } else {
         System.out.println("Component type is null");
      }
   }
}

Output

Component type is int

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements