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



The java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method creates a new array with the specified component type and dimensions. If componentType represents a non-array class or interface, the new array has dimensions.length dimensions and componentType as its component type. If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType. In this case, the component type of the new array is the component type of componentType.


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

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


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

  • dimensions − 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... dimensions) 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,3);

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

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

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

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