Which goes on the stack or heap?

后端 未结 3 1056
北海茫月
北海茫月 2021-01-18 03:06

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;
         


        
相关标签:
3条回答
  • 2021-01-18 03:25

    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

    0 讨论(0)
  • 2021-01-18 03:41

    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.

    0 讨论(0)
  • 2021-01-18 03:46

    Here is an alternate, correct memory diagram.

    0 讨论(0)
提交回复
热议问题