-3

Consider the following program:

int[] arr= new int[2];
.....
System.out.println(arr.length);

In JLS we read that object in java is instance of class or array. But, we see here array of primitive type. So, int[2] is an object too. But, how it was achieved? It was sth like int=>Integer, or int[]=>Integer[] or something else? And by the way, where it resides? In heap or in stack?

Pankaj
  • 592
  • 7
  • 19
avalon
  • 2,231
  • 3
  • 24
  • 49

1 Answers1

3

In Java you only have primitive or references to objects.*

int[] arr = { 1, 2 };
int i = arr[0];
assert arr instanceof Object; // true

arr is a reference to an array which has int as a element.

how it was achieved?

int[] has it's own class int[].class and your arr is an instance of that class.

It was sth like int=>Integer, or int[]=>Integer[] or something else?

Integer is not related at all. to convert an int[] into an Integer[] you have to create a new array and copy every element one by one.

And by the way, where it resides? In heap or in stack?

You can assume all objects are on the heap. Java 8 can place some objects on the stack using Escape Analysis, however I don't believe it can do this for array types.

* the only other type is void which is neither a primitive nor a reference. It has a wrapper Void but you can't have a field or parameter of type void.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I'll tend to say that primitive type arrays are not managed like any "regular" Object arrays see:https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#New_PrimitiveType_Array_routines – Mizux May 12 '20 at 12:31