Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java uses heap for memory allocation? [duplicate]

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 ?

like image 432
Serenity Avatar asked May 07 '10 09:05

Serenity


People also ask

Why does Java use a heap?

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.

Why heap is used for memory allocation?

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.

Does Java use heap memory?

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.

What happens if heap memory is full in Java?

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.


1 Answers

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.

like image 78
Marcelo Cantos Avatar answered Sep 17 '22 15:09

Marcelo Cantos