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 ?
I only have an idea about data structures being a beginner. I mean why not stack or something else ?
Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create an object, it's always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that don't have any reference.
The advantages of heap memory are: Lifetime. Because the programmer now controls exactly when memory is allocated, it is possible to build a data structure in memory, and return that data structure to the caller. This was never possible with local memory, which was automatically deallocated when the function exited.
Heap space is used for the dynamic memory allocation of Java objects and classes at runtime. New objects are always created in the heap space, and references to these objects are stored in the stack memory.
Java objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
The problem with a stack is that you can only remove the most recent thing you added. This works fine for local variables, since they come and go as you enter and exit functions, but not so well for arbitrary data who's lifecycle doesn't follow that of individual functions. The memory heap allows you to add and remove data at will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With