2

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?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
christopher
  • 26,815
  • 5
  • 55
  • 89

4 Answers4

8

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!");
Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

"An array is a container object that holds a fixed number of values of a single type.".This is how array is defined in oracle tutorials.So not only primitive array but also object array is a Object itself.

Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50
-1
int[] x = new int[5];

Object a=(Object)x;

int[] y= (int[])a;
Virus
  • 167
  • 1
  • 11