Java array using stack space

前端 未结 4 1160
心在旅途
心在旅途 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 17:54

    In a word, no.

    The only variables that are stored on the stack are primitives and object references. In your example, the arr reference is stored on the stack, but it references data that is on the heap.

    If you're asking this question coming from C++ because you want to be sure your memory is cleaned up, read about garbage collection. In short, Java automatically takes care of cleaning up memory in the heap as well as memory on the stack.

提交回复
热议问题