java.lang.reflect.Array.newInstance() Method Example



The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method creates a new array with the specified component type and length.


Following is the declaration for java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method.

public static Object newInstance(Class<?> componentType, int length)
   throws IllegalArgumentException, NegativeArraySizeException


  • componentType − the Class object representing the component type of the new array.

  • length − an array of int representing the dimensions of the new array.

Return Value

the new array.


  • NullPointerException − If the specified componentType is null.

  • IllegalArgumentException − if the specified dimensions argument is a zero-dimensional array, or if the number of requested dimensions exceeds the limit on the number of array dimensions supported by the implementation (typically 255), or if componentType is Void.TYPE.

  • ArrayIndexOutOfBoundsException − If the specified index argument is negative.


The following example shows the usage of java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {

      String[] stringArray = (String[]) Array.newInstance(String.class, 3);

      Array.set(stringArray, 0, "Mahesh");
      Array.set(stringArray, 1, "Ramesh");
      Array.set(stringArray, 2, "Suresh");

      System.out.println("stringArray[0] = " + Array.get(stringArray, 0));
      System.out.println("stringArray[1] = " + Array.get(stringArray, 1));
      System.out.println("stringArray[2] = " + Array.get(stringArray, 2));

Let us compile and run the above program, this will produce the following result −

stringArray[0] = Mahesh
stringArray[1] = Ramesh
stringArray[2] = Suresh