简体   繁体   中英

java primitive type array object or not?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM