4. Compare to stack memory and heap memories.

Here is the different point between Heap and Stack. Comment if you need me explain something!

 

Heap

Stack
Java Heap Memory is the memory used at runtime to store Objects. Whenever anywhere in your program when you create an Object it will be stored in the Heap (execute the new operator) Stack Memory is memory to store local variables in functions and function calls at runtime in a java Thread. Local variables include: primitive types, reference types to objects in the heap (reference), declarations in functions, or arguments passed to the function.
Objects stored in the heap are globally accessible Stack memory is used only by one thread of execution.
Heap’s management mechanism is more complex. Heap is divided into 2 types Young-Generation, Old-Generation. (Garbage Collection) The operating mechanism is LIFO (Last-In-First-Out)
Heap memory lives from the start till the end of application execution. Stack memory is short-lived.

Explainations:

The Stack memory is used to store local variables (local variables) inside the function, this memory area is used to hold the value of the parameters when called. When a function ends, the Stack memory area will be automatically released. The stack uses a LIFO (last in, first out) structure.

Java Heap Memory is the memory used at runtime to store Objects. Heap memory must be freed through a function by the programmer (however, in some languages ​​today there is a function to automatically collect and free memory like Garbage Collection in Java, C#).

void main() 
{
    int *a = null;            //Create on Stack memory area
    int b;                    //Create on Stack memory area
         int c = 5;           //Create on Stack memory area
         *a = new int[100];   //Create an array of 500 int variables on the Heap memory area
    }                         //Free c but not the memory area that a points to
    delete[] a;               //Free the int array that a points to
}                             //Free a and b

 

Leave a Reply

Your email address will not be published. Required fields are marked *