Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...