Java array using stack space

前端 未结 4 1156
心在旅途
心在旅途 2020-12-11 17:15

This is the usual way for declare a Java array:

int[] arr = new int[100];

But this array is using heap space. Is there a way we can declare

4条回答
  •  温柔的废话
    2020-12-11 18:07

    Arrays are dynamically allocated so they go on the heap.

    I mean, what happens when you do this:

    int[] arr = new int[4];
    arr = new int[5];
    

    If the first allocation was done on the stack, how would we garbage collect it? The reference arr is stored on the stack, but the actual array of data must be on the heap.

提交回复
热议问题