Java - Array Class Type

Introduction

Arrays are objects.

The following code illustrates how to get the class name of an array.

Demo

public class Main {
  public static void main(String[] args) {
    int[] iArr = new int[2];
    int[][] iiArr = new int[2][2];
    int[][][] iiiArr = new int[2][2][2];

    String[] sArr = { "A", "B" };
    String[][] ssArr = { { "AA" }, { "BB" } };
    String[][][] sssArr = {}; // A 3D empty array of string

    // Print the class name for all arrays
    System.out.println("int[]:" + getClassName(iArr));
    System.out.println("int[][]:" + getClassName(iiArr));
    System.out.println("int[][][]:" + getClassName(iiiArr));
    System.out.println("String[]:" + getClassName(sArr));
    System.out.println("String[][]:" + getClassName(ssArr));
    System.out.println("String[][][]:" + getClassName(sssArr));
  }/*from ww  w.ja v a 2  s .  c  o m*/

  public static String getClassName(Object obj) {
    Class c = obj.getClass();
    String className = c.getName();
    return className;
  }
}

Result

Array Class Name

The class name of an array starts with left bracket(s) [.

The number of left brackets is equal to the dimension of the array.

For an int array, the left bracket(s) is followed by a character I.

For a reference type array, the left bracket(s) is followed by a character L, followed by the name of the class name.

The class names for one-dimensional primitive arrays and a reference type are shown in the following table.

Array Type Class Name
byte[] [B
short[] [S
int[] [I
long[] [J
char[] [C
float[] [F
double[][D
boolean[] [Z
com.book2s.Person[] [Lcom.book2s.Person;