Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the class of the Arrays in Java

Tags:

java

arrays

Arrays are Objects and all the objects come from a class. If I execute the following code:

public class Test {
    public static void main(String[] args) {
        String str = "Hello";
        System.out.println(str.getClass());
    }
}

The output is class java.lang.String.

But if I execute the following:

public class Test {
    public static void main(String[] args) {
        int arr[] = new int[10];
        System.out.println(arr.getClass());
    }
}

The output is class [I.

My questions are:

  1. What is the class of the arrays?
  2. Why is it the result?
  3. If I would like to use the instanceof operator how should I use it? If I execute System.out.println(arr instanceof Object);, it works perfectly.
like image 338
Alejandro Agapito Bautista Avatar asked Jun 25 '15 16:06

Alejandro Agapito Bautista


2 Answers

Adding to the other answer, the type can actually be decoded using the string you got as desscribed in JVMS: Chapter 4. The class File Format:

B   byte    signed byte
C   char    Unicode character code point in the Basic Multilingual Plane, encoded with UTF-16
D   double  double-precision floating-point value
F   float   single-precision floating-point value
I   int     integer
J   long    long integer
L ClassName ;   reference   an instance of class ClassName
S   short   signed short
Z   boolean     true or false
[   reference   one array dimension

What you got was class [I. So [ which is an array dimension and I which is an integer. An array of integers describes the type.

like image 22
Reut Sharabani Avatar answered Nov 07 '22 07:11

Reut Sharabani


This is all specified in the JLS. Arrays are dynamically created Objects which implement Serializable and Cloneable.

The reason you're seeing that come across is due to that being the way the object is represented in Class#getName.

Because you can use instanceof with reifiable Object types, and an array is very much reifiable (i.e. concrete, not generic), you can use instanceof with arrays:

System.out.println(arr instanceof int[]);    // true
System.out.println(arr instanceof String[]); // false

The issue with your arr instance Object is that <X> instanceof Object isn't useful, since everything is an Object (except primitives, but using instanceof with primitives is a compile-time error).

like image 66
Makoto Avatar answered Nov 07 '22 06:11

Makoto