Which goes on the stack or heap?

I am doing some studying and I came across a question that asks to show the correct memory diagram of the following code:

int [] d1 = new int[5];
d1[0] = 3;

Integer [] d2 = new Integer[5];
d2[0] = new Integer(3);

ArrayList d3 = new ArrayList();
d3.add(3);

Here is my attempt at a memory diagram, but it may be incorrect:

在这里输入图像描述

I understand things like objects, instance variables, and "new" instances are all on the heap and things such as local variables and primitive types are on the stack, but I'm still confused when it comes to array types.

Any help is appreciated.


Any Object on Java lives on heap.

In Java Array is also an Object and hence array Object lives on heap.

Explaination:-

When you write

int a=new int[5],

the (new int[5]) part creates object and hence lives on heap.

Integer x=new Integer(10000)

is also an Object(remember new Operator will always create new Object).

and hence when you wright,

Integer [] d2 = new Integer[5];

it is Array of Integer Object.

As far as ArrayList is considered it is also a class but it wraps array Object and adds dynamic memory to it. So,

ArrayList d3 = new ArrayList();

again creates Object and hence live on heap.

Consider ArrayList class as:

class ArrayList{
    int index=0;
    Object[] obj=new Object['some integer value (depends on JVM)'];
    public void add(Object o){
        obj[index]=o;
        index++;
    }
    //other methods
}

so when you write d3.add(5) actually d3.add(new Integer(5)) is being called.

Remember one golden rule: In java whatever Object you create live on HEAP and their reference live on stack.

Proof of array being object:-

int[] a={4,3,1,2};
System.out.println(a instanceof Object);

//prints true


Arrays are not primitive in java it has concrete class in java.

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.

System.out.print(int[].class.toString());

So when you create Object of any array type it must go to you heap space.


这是一个备用的,正确的内存图。

链接地址: http://www.djcxy.com/p/13866.html

上一篇: 垃圾收集器在堆中移动数据时引用是否更新?

下一篇: 哪一个会堆栈或堆?