where is array saved in memory in java?

后端 未结 4 2250
半阙折子戏
半阙折子戏 2021-01-04 08:19

If I have a function that in that function I declare:

Object arr[] = new Object[20];

Where are arr and the whole array stored? heap? stack?

4条回答
  •  一生所求
    2021-01-04 09:16

    In theory, the stack has a single pointer to a location in the heap that contains the array itself. The array itself is just an array of pointers which also point to locations in the heap that contain the objects you reference.

    In Java, you can pretty much count on the fact that any time you say new ..., space is being created in the heap. Generally speaking, any time you declare a variable, the compiler will reserve stack space in the method's context for that variable. For native types, that space will hold the actual bytes to represent the value. For objects and arrays, that variable will hold a memory reference.

    So, for example, the following objects have separate memory locations allocated for them in the heap:

    new Object[20]
    new String("abc")
    new List() // This contains a reference to an initial array, which is also on the heap.
    

    Note that there are very few times when new String("abc") is preferable to "abc", since string literals are going to exist in the package's memory anyway, and strings are immutable. There's no point allocating extra memory for an exact copy of a string that exists in memory already.

    In practice, the only caveat is that the compiler doesn't necessarily have to store local variables on the stack at all. If it determines that the scope of the variable is short enough, it's free to optimize away the stack reference and just use a register for it.

提交回复
热议问题