Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Array.newInstance — creating arrays dynamically

Array.newInstance creates arrays from a Class<?> object. It supports primitive types, reference types, and multiple dimensions.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static Object newInstance(Class<?> componentType, int length)
public static Object newInstance(Class<?> componentType, int... dimensions)

Array.newInstance from java.lang.reflect.Array creates an array when its type is available as Class<?>. It returns Object; any cast must match the actual array type.

The int length overload adds one dimension. The int... dimensions overload accepts successive dimension lengths. If componentType already represents an array, new dimensions are added to its existing dimensions; the total limit is 255.

int.class creates a primitive array, whereas Integer.class creates a reference array. An int[] is not an Object[].

A negative length causes NegativeArraySizeException. An empty dimensions list, void.class, or exceeding the limit causes IllegalArgumentException; a null componentType causes NullPointerException. Zero lengths are allowed.

Examples

import java.lang.reflect.Array;

public class Main {
    public static void main(String[] args) {
        Class<?> componentType = int.class;
        int[] values = (int[]) Array.newInstance(componentType, 3);
        values[1] = 7;
        System.out.println(values.length + ":" + values[1]);

        int[][] grid = (int[][]) Array.newInstance(componentType, 2, 3);
        grid[1][2] = 9;
        System.out.println(grid.length + "x" + grid[0].length + ":" + grid[1][2]);
    }
}

Result

3:7
2x3:9

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources