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:
instanceof
operator how should I use it? If I execute System.out.println(arr instanceof Object);
, it works perfectly.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.
This is all specified in the JLS. Arrays are dynamically created Object
s 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With