Why does Java uses heap for memory allocation?

前端 未结 7 527
别那么骄傲
别那么骄傲 2020-12-09 11:15

I just read this statement in a java book saying Objects in java reside on a heap. Is a heap used because it is the best way to store data and retrieve data fast ?

7条回答
  •  执念已碎
    2020-12-09 11:35

    Because Java uses a garbage collector to reclaim memory, unlike C and C++. In those languages it makes sense to use the stack for local variables*. In Java, there is no concept of a (local) variable going out of scope, only it is not referenced anymore, which makes it eligible for garbage collection (which is bound to happen sometime after that point).

    * which, for the sake of clarity, does not mean that there were no heap in C/C++, or that you could not use the malloc/new family to allocate variables to be used solely within local scope.

提交回复
热议问题