Which goes on the stack or heap?

孤街醉人 提交于 2019-12-01 16:59:31

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.

Here is an alternate, correct memory diagram.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!