Had a look, and I can't seem to find a question that is the same as this. My question is about int[] in Java.
When you create an int[], you use this syntax:
int[] x = new int[5];
The methods that are part of int[] also make me think it's an Object, but it doesn't follow the Java naming convention for classes, which is what's confusing me. It is also an array of a primitive type, which can be used like a primitive.
Is an int[] (or any primitive array I guess) an object, or a primitive?
An array in Java is a subclass of Object, therefore it's an object type - even if it contains primitive types. You can check this:
int[] x = new int[5];
if (x instanceof Object)
System.out.println("It's an Object!");
All arrays in Java are considered objects. You can see this in the Java Language Specification, Ch. 10:
In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
The type int[] is a subclass of Object that has all the method from Object. Although syntactically it looks different from other object types (e.g. the name has a primitive type listed in it and there's no class definition), the Java language does consider them objects.
Hope this helps!
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